gladly-team / next-firebase-auth

Simple Firebase authentication for all Next.js rendering strategies
https://nfa-example-git-v1x-gladly-team.vercel.app/
MIT License
1.34k stars 290 forks source link

IdToken not being set as authorization header in axios interceptor on page load. #681

Closed ameer-khan-ashraf closed 9 months ago

ameer-khan-ashraf commented 1 year ago

I am setting the idToken as authorization header for a standalone backend for my project as follows

import axios from "axios";
import { getApp } from "firebase/app";
import { getAuth } from "firebase/auth";

  const auth = getAuth(getApp());
  export const axiosInstance = axios.create({
    baseURL: process.env.NEXT_PUBLIC_BASE_URL
  });
// Intercept request
  axiosInstance.interceptors.request.use(
    async function (config) {
      const idToken = await auth.currentUser?.getIdToken();
      console.log(idToken)
      if (idToken) {
        config.headers.Authorization = `Bearer ${idToken}`;
      }
      return config;
    },
    function (error) {
      return Promise.reject(error);
    }
  );

However whenever I refresh the first few requests are being rejected from the backend as they dont have any idToken. but if I navigate to another page or initiate a request after the page load they work fine.

The only way to bypass this is to store the token in localstorage and access from there for the first few request and then the firebasek keeps refreshing and updating the localstorage once they have user in auth. but this causes another issue where the token expires if the screen is left open for too long and the api returns a 403 error. the backend is a standalone backend made using flask.

Am I missing something in the implementation? is there another way to get the idToken in non react component when using this library? Thanks in advance for the help.