Skip to content
Advertisement

Accessing id token of firebase 9 in axios interceptor directly

Is there a way to get the id token from firebase 9 directly in the axios interceptor? It was possible with firebase 8.

import axios from "axios";
import config from "../config";
import { getAuth, getIdToken } from "firebase/auth";

const API = axios.create({
  responseType: "json",
  baseURL: config.ApiUrl
});

API.interceptors.request.use(async (request) => {
  const auth = getAuth();
  const { currentUser } = auth;
  
  request.headers = {
    Authorization: `Bearer ${await currentUser.getIdToken()}`,
  };
  return request;

});

currentUser is null first because it is loaded async by firebase. How can I access it directly without always having the problem that the first time it crashes because the user is not loaded yet?

Thank your for your help.

Advertisement

Answer

You can create a function that waits for onAuthStateChanged() to load auth state and returns a promise containing user’s token. Try:

const getUserToken = async () => {
  return new Promise((resolve, reject) => {
    const unsub = onAuthStateChanged(getAuth(), async (user) => {
      if (user) {
        const token = await getIdToken(user);
        resolve(token)
      } else {
        console.log("User not logged in")
        resolve(null)
      }
      unsub();
    });
  })
}
API.interceptors.request.use(async (request) => {
  const token = await getUserToken();

  if (token) {
    request.headers = {
      Authorization: `Bearer ${token}`,
    };
  } else {
    // prompt user to login?
  }

  return request;
});

Make sure you have initialized Firebase SDK before using getAuth(). I recommend creating a different file firebase.js, initialize required services and exporting the instances as explained in this answer.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement