The Supabase UE5 Plugin implements enterprise-grade connection management through a centralized subsystem architecture. This system provides automatic health monitoring, session persistence, token refresh automation, and robust error recovery mechanisms designed for production game environments.
All connections are managed through the USupabaseSubsystem, ensuring:
GameInstance
└── USupabaseSubsystem (Singleton)
├── USupabaseConnection (Configuration)
├── USupabaseClient (HTTP Operations)
└── Connection State Management
Primary configuration object containing all connection parameters:
UCLASS()
class USupabaseConnection : public UPrimaryDataAsset
{
// Connection Identity
UPROPERTY(BlueprintReadWrite, EditAnywhere)
FName ConnectionName; // "Main", "Analytics", etc.
// Server Configuration
UPROPERTY(BlueprintReadWrite, EditAnywhere)
FString SupabaseServerUrl; // https://your-project.supabase.co
// Authentication Credentials
UPROPERTY(BlueprintReadWrite, EditAnywhere)
FSupabaseCredentials SupabaseCredentials;
// Connection State
UPROPERTY(BlueprintReadWrite, EditAnywhere)
bool bIsAuthenticated;
};
Secure storage and management of authentication keys:
struct FSupabaseCredentials
{
FString AnonymousKey; // Public operations (ey...)
FString ServiceKey; // Admin operations (ey...)
FString UserAuthenticatedKey; // User-specific JWT token
FString RefreshToken; // Token renewal
};
Best practice setup in your game instance:
void AMyGameInstance::BeginPlay()
{
Super::BeginPlay();
// Get the subsystem (automatically created by UE5)
USupabaseSubsystem* Supabase = GetSubsystem<USupabaseSubsystem>();
// Create connection configuration
USupabaseConnection* Connection = NewObject<USupabaseConnection>();
Connection->ConnectionName = TEXT("Main");
Connection->SupabaseServerUrl = TEXT("https://your-project.supabase.co");
Connection->SupabaseCredentials.AnonymousKey = TEXT("your-anon-key");
Connection->SupabaseCredentials.ServiceKey = TEXT("your-service-key");
// Initialize the connection
bool bSuccess = Supabase->InitializeConnection(Connection);
if (bSuccess)
{
// Bind to connection events
Supabase->OnConnectionStateChanged.AddDynamic(
this, &AMyGameInstance::OnSupabaseConnectionChanged
);
Supabase->OnAuthenticationStateChanged.AddDynamic(
this, &AMyGameInstance::OnSupabaseAuthChanged
);
UE_LOG(LogTemp, Log, TEXT("Supabase connection initialized successfully"));
}
}
Simplified Blueprint initialization:
Event BeginPlay
├── Get Game Instance
├── Get Subsystem (Supabase Subsystem)
├── Create Supabase Connection
│ ├── Set Connection Name: "Main"
│ ├── Set Server URL: "https://your-project.supabase.co"
│ └── Set Credentials (Anonymous Key, Service Key)
└── Initialize Connection
├── Bind Event: On Connection State Changed
└── Bind Event: On Authentication State Changed
The subsystem continuously monitors connection health:
// Health check configuration
const float ConnectionTestInterval = 300.0f; // 5 minutes
const float TokenRefreshInterval = 3300.0f; // 55 minutes
const int32 MaxConnectionRetries = 3; // Retry attempts
IsLoggedIn() endpointvoid USupabaseSubsystem::OnConnectionHealthCheck()
{
if (bDebugLogging)
{
UE_LOG(LogTemp, Verbose, TEXT("Performing connection health check"));
}
TestConnection();
}
void USupabaseSubsystem::TestConnection()
{
if (!SupabaseClient || !ActiveConnection)
{
SetConnectionState(false);
return;
}
// Lightweight health check
SupabaseClient->IsLoggedIn();
}
Robust retry mechanism with intelligent backoff:
void USupabaseSubsystem::RetryConnection()
{
if (ConnectionRetryCount >= MaxConnectionRetries)
{
UE_LOG(LogTemp, Error, TEXT("Max connection retry attempts reached"));
SetConnectionState(false);
return;
}
ConnectionRetryCount++;
UE_LOG(LogTemp, Warning, TEXT("Retrying connection (attempt %d/%d)"),
ConnectionRetryCount, MaxConnectionRetries);
TestConnection();
}
Proactive token renewal to prevent authentication expiration:
void USupabaseSubsystem::OnTokenRefreshCheck()
{
if (bIsAuthenticated && !ActiveConnection->SupabaseCredentials.RefreshToken.IsEmpty())
{
if (bDebugLogging)
{
UE_LOG(LogTemp, Verbose, TEXT("Performing token refresh"));
}
RefreshToken();
}
}
Automatic save/restore of authentication state:
// Session data automatically persisted
struct FTokenResponse
{
FString AccessToken; // JWT access token
FString TokenType; // "Bearer"
int32 ExpiresIn; // 3600 (seconds)
int64 ExpiresAt; // Unix timestamp
FString RefreshToken; // Refresh token
FUser User; // User profile data
};
The subsystem maintains comprehensive connection state:
// Connection state variables
bool bIsConnected; // Network connectivity to Supabase
bool bIsAuthenticated; // User authentication status
bool bIsInitialized; // Subsystem initialization complete
bool bDebugLogging; // Detailed logging enabled
Automatic broadcasting of state changes to all listeners:
// Connection state events
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(
FOnConnectionStateChanged, bool, bIsConnected
);
DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(
FOnAuthenticationStateChanged,
bool, bIsAuthenticated,
const FUser&, User
);
Responding to connection state changes:
UFUNCTION()
void AMyGameInstance::OnSupabaseConnectionChanged(bool bIsConnected)
{
if (bIsConnected)
{
UE_LOG(LogTemp, Log, TEXT("Supabase connected successfully"));
// Enable online features
EnableOnlineFeatures();
}
else
{
UE_LOG(LogTemp, Warning, TEXT("Supabase connection lost"));
// Switch to offline mode
EnableOfflineMode();
}
}
UFUNCTION()
void AMyGameInstance::OnSupabaseAuthChanged(bool bIsAuthenticated, const FUser& User)
{
if (bIsAuthenticated)
{
UE_LOG(LogTemp, Log, TEXT("User authenticated: %s"), *User.Email);
// Load user-specific data
LoadUserProfile(User);
}
else
{
UE_LOG(LogTemp, Log, TEXT("User logged out"));
// Clear user data
ClearUserSession();
}
}
Comprehensive error recovery strategies:
// Automatic retry with exponential backoff
void HandleConnectionFailure()
{
// 1. Log the failure
UE_LOG(LogTemp, Warning, TEXT("Connection failure detected"));
// 2. Update connection state
SetConnectionState(false);
// 3. Attempt automatic recovery
RetryConnection();
// 4. Notify listeners
OnConnectionStateChanged.Broadcast(false);
}
Built-in handling for common network scenarios:
Graceful degradation when connection is unavailable:
bool IsOfflineMode() const
{
return !bIsConnected || !ActiveConnection;
}
// Operations automatically queue for later sync
void QueueOperationForLaterSync(const FString& Operation, const FJsonObject& Data)
{
if (IsOfflineMode())
{
PendingOperations.Add({Operation, Data, FDateTime::Now()});
}
}
Comprehensive logging system for troubleshooting:
void USupabaseSubsystem::EnableDebugLogging(bool bEnable)
{
bDebugLogging = bEnable;
if (SupabaseClient)
{
SupabaseClient->ChangeDebugOutput(bEnable);
}
UE_LOG(LogTemp, Log, TEXT("Supabase debug logging %s"),
bEnable ? TEXT("enabled") : TEXT("disabled"));
}
Built-in validation for connection parameters:
bool ValidateConnection(USupabaseConnection* Connection)
{
if (!Connection)
{
UE_LOG(LogTemp, Error, TEXT("Connection object is null"));
return false;
}
if (Connection->SupabaseServerUrl.IsEmpty())
{
UE_LOG(LogTemp, Error, TEXT("Server URL cannot be empty"));
return false;
}
if (!Connection->SupabaseServerUrl.StartsWith(TEXT("https://")))
{
UE_LOG(LogTemp, Error, TEXT("Server URL must use HTTPS"));
return false;
}
if (Connection->SupabaseCredentials.AnonymousKey.IsEmpty())
{
UE_LOG(LogTemp, Error, TEXT("Anonymous key is required"));
return false;
}
return true;
}
Built-in metrics for connection performance:
struct FConnectionMetrics
{
int32 TotalRequests; // Total HTTP requests made
int32 SuccessfulRequests; // Successful responses
int32 FailedRequests; // Failed responses
float AverageResponseTime; // Average response time (ms)
int32 ConnectionRetries; // Number of retry attempts
FDateTime LastSuccessfulPing; // Last successful health check
};
Support for multiple Supabase projects:
// Multiple connections for different purposes
InitializeConnection(MainConnection); // Primary game data
InitializeConnection(AnalyticsConnection); // Analytics/telemetry
InitializeConnection(ChatConnection); // Real-time chat
Dynamic connection management:
// Switch active connection
UFUNCTION(BlueprintCallable)
void SetActiveConnection(USupabaseConnection* Connection)
{
if (ValidateConnection(Connection))
{
ActiveConnection = Connection;
// Reinitialize client with new connection
if (SupabaseClient)
{
SupabaseClient->SetConnection(Connection);
}
// Restart health monitoring
StartConnectionHealthChecks();
}
}
GameInstance::BeginPlay() for global availabilitySymptoms: Operations hang without response
Solution: Check network connectivity, verify server URL, increase timeout values
Symptoms: "Invalid JWT" or "Access denied" errors
Solution: Verify credentials, check token expiration, ensure proper key usage
Symptoms: Periodic connection loss and recovery
Solution: Check network stability, adjust health check intervals, implement better retry logic
Symptoms: Increasing memory usage over time
Solution: Ensure proper cleanup, check async operation lifecycle, monitor object references
// Enable verbose logging
USupabaseManager::EnableDebugLogging(this, true);
// Test connection manually
USupabaseManager::TestConnection(this);
// Check current status
bool bConnected = USupabaseManager::IsConnected(this);
bool bAuthenticated = USupabaseManager::IsAuthenticated(this);
// Get connection metrics
FConnectionMetrics Metrics = Subsystem->GetConnectionMetrics();
Key log messages to monitor:
LogTemp: Supabase connection initialized successfully
LogTemp: Performing connection health check
LogTemp: Token refresh successful
LogTemp: Warning: Connection retry attempt (2/3)
LogTemp: Error: Max connection retry attempts reached
Real-time monitoring of connection health:
USTRUCT(BlueprintType)
struct FConnectionStatus
{
UPROPERTY(BlueprintReadOnly)
bool bIsHealthy; // Overall health status
UPROPERTY(BlueprintReadOnly)
float LastPingTime; // Last successful ping (ms)
UPROPERTY(BlueprintReadOnly)
int32 ConsecutiveFailures; // Consecutive failed health checks
UPROPERTY(BlueprintReadOnly)
FDateTime LastSuccessfulConnection; // Last successful operation
UPROPERTY(BlueprintReadOnly)
FString ConnectionQuality; // "Excellent", "Good", "Poor", "Offline"
};
Automatic alerts for critical connection issues:
// Critical connection events
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(
FOnConnectionCritical, FString, ErrorMessage
);
// Performance degradation warnings
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(
FOnConnectionDegraded, float, ResponseTime
);
This connection management system provides enterprise-grade reliability while maintaining simplicity for developers. The automatic health monitoring, token refresh, and error recovery ensure your game maintains consistent connectivity to Supabase services across all platforms and network conditions.