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);
}
);