Description
Is your feature request related to a problem? Please describe.
Hello,
We're encountering a problem related to initializing the Supabase client in a background isolate. Specifically, we use accessToken
inside a background task (triggered via Firebase's _firebaseMessagingBackgroundHandler) to authenticate the user with one of our services, which shares authentication across services.
Problem
We need to refresh the token when it's expired. To do that, we attempt to initialize the Supabase client (if not already initialized). However, when doing this from a background isolate, we encounter one of two errors:
We get either:
Error 1: [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: 'package:supabase_flutter/src/supabase.dart': Failed assertion: line 91 pos 7: '!_instance._initialized': This instance is already initialized
OR, if we try to check currentSession
to determine whether to re-initialize Suapabse or not, we get an error saying that we must initialize the Supabase instance first:
Error 2: Unhandled Exception: 'package:supabase_flutter/src/supabase.dart': Failed assertion: line 45 pos 7: '_instance._initialized': You must initialize the supabase instance before calling Supabase.instance
E/flutter (24643): #0 _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:50:61)
This creates a catch-22 scenario: if we try to access Supabase.instance, it throws because it’s not initialized. If we try to initialize it, it may throw because it is already initialized (perhaps in another isolate or due to isolate state desync).
We've also tried manually disposing Supabase when the app is paused, but this does not resolve the issue.
Describe the solution you'd like
We propose exposing an isInitialized flag on the Supabase class to allow a safe check before initialization. For example:
if (!Supabase.isInitialized) {
await Supabase.initialize(
url: AppConfig.supabaseUrl,
anonKey: AppConfig.supabasePublicAnonKey,
);
}
or, if feasible, a force
flag which should dispose instance and initialize it back again.
await Supabase.initialize(
url: AppConfig.supabaseUrl,
anonKey: AppConfig.supabasePublicAnonKey,
force: true
);
Describe alternatives you've considered
We currently cache the accessToken outside of Supabase, but this is not a reliable production solution. If the token expires, we can’t proceed with authenticated requests, leading to failed background operations.
Environment
supabase_flutter: ^2.9.0
Thank you for considering this.