Supbase session expired after some hours can't retrive user id from Flutter app
01:01 05 Nov 2025

I am trying to get the userId from the current user session. It work when a user logged in but after some hours if app inactive the function can't retrive the userId from the session?

My Code:

Supabase Initialize:

static Future initialize() async {
    await Supabase.initialize(
        url: SupabaseConfig.serviceUrl,
        anonKey: SupabaseConfig.anonKey,
        authOptions: FlutterAuthClientOptions(
          autoRefreshToken: true,
          localStorage: SharedPreferencesLocalStorage(persistSessionKey: 'userSession'),
        ));

The approch i have tried for get the userId:

  static Future getUserId() async {
    final client = SupabaseService.client;

    var user = client.auth.currentUser;

    if (user == null) {
      final session = client.auth.currentSession;
      if (session != null) {
        try {
          final refreshedSession = await client.auth.refreshSession();
          user = refreshedSession.user;
        } catch (e) {
          return null;
        }
      } else {
        return null;
      }
    }
    logger.d(user?.id);
    return user?.id;
  }

On my bloc i have used this below code:

on(
      (event, emit) async {
        final hasUserDetails = await UserData.getUserId();
        hasUserDetails != null || hasUserDetails!.isNotEmpty ? emit(AuthUserSignedIn()) : emit(AuthSignedOut());
      },
    );

The bloc check the userid if not null then state = AuthUserSignedIn() which is work fine if condition is user logged in and eveytime the app open it state AuthUserSignedIn() but when we tried to access the user id to get some user details like:

  static Future getUserBasicInfo() async {
    final userId = await getUserId();
    if (userId == null) return null;
    try {
      final respond = await SupabaseService.client.from("users").select("name, profileurl").eq('uuid', userId).single();
      AppUserData.setStringList(key: UserDataKeys.basicInfo, list: [respond['name'], respond['profileurl']]);
      return UserBasicInfoModel.fromJson(respond);
    } catch (e) {
      return null;
    }
  }

Here the userId return null ?


It supposed to be return the userId from the code Supabase.instance.client.auth.currentUser.id but not work. There is something wrong. I have read the documentation their mention the the session will expire under 5 to 1 hours so my question is if my approch not working then how to return the session and get the userId with the right approch?

flutter supabase supabase-flutter