0

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);
  }
);
Sudip Shrestha
  • 321
  • 1
  • 9

1 Answers1

1

There is a lot written on the subject of how best to store authentication tokens in frontend applications. There are several solutions and each has its pros and cons. This previous answer might give you some ideas.

This article gives a nice overview and explains why storing in memory might be the best option. Here is another article with a similar conclusion

In your case, you might store the token in memory. When required, check for its existence, and if it is not in memory (think browser refresh) make the call to Firebase to retrieve the token and store it in memory again.

Of course, you should look at your specific context and needs and decide if any of the other solutions, such as localStorage, might work for you and your security requirements.

Russell Ormes
  • 525
  • 8
  • 22