Supabase: Invalid JWT after having app running for some time

215 Views Asked by At

I am calling

await Supabase.initialize(
  url: config.api.url,
  anonKey: config.api.anonKey,
);

in my main.dart and later using this code to call an Edge-Function:

final authHeader = Supabase.instance.client.auth.headers['Authorization'] ?? '';
SseClient(
    http.Request(
      'POST',
      Uri.parse('${getConfigFromEnv().api.url}/functions/v1/chat_stream'),
    )
      ..headers.addAll({
        'Authorization': authHeader,
        'Content-Type': 'application/json',
      })
      ..body = jsonEncode(data),
    httpClientProvider: http.Client.new,
    );
}

This works fine! But if my app is open for some time, it seems that my JWT expires and when I trigger the Edge-Function again, I get Invalid JWT as a response.

What do I have to do to make sure, that the auth.headers are renewed?

Thanks a lot!

1

There are 1 best solutions below

4
On

You can call the refreshSession() method to make sure the token is fresh.

await supabase.auth.refreshSession();
final authHeader = Supabase.instance.client.auth.headers['Authorization'] ?? '';
SseClient(
    http.Request(
      'POST',
      Uri.parse('${getConfigFromEnv().api.url}/functions/v1/chat_stream'),
    )
      ..headers.addAll({
        'Authorization': authHeader,
        'Content-Type': 'application/json',
      })
      ..body = jsonEncode(data),
    httpClientProvider: http.Client.new,
    );
}