Refresh Firebase Token using API Interceptors

Actions & Logic

I have a new web app. Regularly users go away and leave the webapp opened in their browsers.

After an hour the token has expired, but the app stands still in their browsers where they left. When they come back and click any button that triggers a backend API request, I get a "grey" screen because my API responded with a 401 (i.e. token has expired). A simple refresh (F5) solve the issue, but I do not this experience to my users.

So I decided to fix it, and a way I found I could do it is to make use of API interceptors, in which it could check before the request if the token is not valid (expired) and call a refresh token behind the scenes and move forward. This would make a seamless experience to my beloved users.

I couldn't find any place where I could find a suitable code for that. I found, however, a nice example from flutterflow youtube channel explaining about interceptors (https://www.youtube.com/watch?v=L5qj2f9skt4).

The example is exactly what I need, and the coded I spotted from the video is like this:

// DO NOT REMOVE OR MODIFY THE CODE ABOVE!

import '/backend/api_requests/api_interceptor.dart';

class TokenCheckInterceptor extends FFApiInterceptor {
  @override
  Future<ApiCallOptions> onRequest({
    required ApiCallOptions options,
  }) async {
    // Perform any necessary calls or modifications to the [options] before
    // the API call is made.
    final isAuthTokenValid = await checkIfAuthTokenValid(currentAuthToken);
    if (!isAuthTokenValid) {
      print("REFRESHING TOKEN");
      await actions.refreshAuthToken();
    }
    options.headers['Authorization'] = 'Bearer $currentAuthToken';
    return options;
  }

  @override
  Future<ApiCallResponse> onResponse({
    required ApiCallResponse response,
    required Future<ApiCallResponse> Function() retryFn,
  }) async {
    // Perform any necessary calls or modifications to the [response] prior
    // to returning it.
    return response;
  }
}

Of course there were failures in the code, such as

The method 'checkIfAuthTokenValid' isn't defined for the type 'TokenCheckInterceptor'. Try correcting the name to the name of an existing method, or defining a method named 'checkIfAuthTokenValid'.  

and

Undefined name 'currentAuthToken'. Try correcting the name to one that is defined, or defining the name.

and

Undefined name 'actions'. Try correcting the name to one that is defined, or defining the name.

What are the remaining pieces that I have to setup to make this interceptor a working piece of software that will make my users happy?

What have you tried so far?

Searched the whole internet for a working example

Did you check FlutterFlow's Documentation for this topic?
Yes
3
4 replies