Retrieve refreshToken in Firebase with customToken

1 June 2024
react-native-firebase
react-native

1. The problem

Using Firebase to build mobile apps can significantly speed up development. However, there are times when you need access to the refresh token for customized behaviour in authentication.

For example, imagine a feature that allows users to switch to a different account within the app without re-logging in. In this case, you need to store the refreshToken securely in the app and use it to exchange for a new access token.

The issue I encountered was that the refreshToken exists on the iOS platform but not on Android when using @react-native-firebase/auth version 18.8.0 as of this writing.

2. The solution

To solve this problem, you can follow these steps:

  1. Get idToken from mobile app
  2. Exchange for customToken from your backend server
  3. Use signInWithCustomToken with Google's API
  4. Read refreshToken from JSON

Here's a sample code snippet to illustrate this process:

  let refreshToken = null;

  const response = await fetch(
    `https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${FIREBASE_API_KEY}`,
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        token: data.customToken,
        returnSecureToken: true,
      }),
    },
  );
  const json = await response.json();
  refreshToken = json?.refreshToken;

Now you have the refreshToken that you can use for your app's custom authentication flow.

Thank you for reading! Cheers!