'What is the best way to send firebase user token from frontend to backend in API Auth header without having to fetch token each time ? (NextJs))

I need to send firebase user token in API authorization header in each API request in my next.js app.

Current Implementation:

axios.interceptors.request.use(
  async (config) => {
    const token = await firebase.auth().currentUser?.getIdToken(true);
    if (token) {
      config.headers["Authorization"] = "Bearer " + token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
)

But the issue with this implementation is to User Token from firebase is fetched before each request which is effecting the performance of the applications.

Is there a better way to implement it ? I am thinking to store the token in local storage and get token from localStorage instead of firebase.

firebase.auth().onAuthStateChanged(async (user) => {
  try {
    if (user) {
      const token = await user.getIdToken(true);
      await localStorage.setItem("app_session", token);
     }
   } catch (err) =>{
        // Handle error
   }
}

And use it like this

axios.interceptors.request.use(
  async (config) => {
    const token = localStorage.getItem("app_session");
    if (token) {
      config.headers["Authorization"] = "Bearer " + token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source