I am building an App using firebase authentication. I pass in the firebase token to the API auth headers to validate the API.
The issue is after 1 hour the token expires and the API does not work anymore? How can I refresh the auth token every time it expires so that essentially the token never expires when the user is logged in.
I am using a auth context
here is AuthContext.jsx
function getRefreshToken() {
auth.onIdTokenChanged(async (user) => {
await user?.getIdToken().then(async (token) => token);
});
}
useEffect(() => {
// setInterval(() => {
// auth.onIdTokenChanged(async (user) => {
// await user?.getIdToken(true).then((token) => {
// setCurrentUser({
// ...currentUser,
// user: user || null,
// isVerified: user ? user.emailVerified : false,
// email: user ? user.email : '',
// accessToken: user ? token : '',
// });
// console.log(token, 'token');
// });
// });
// logout();
// }, 3300000); // every 55 minutes set the access token to the new idToken
const unsubscribe = auth.onAuthStateChanged((user) => {
setCurrentUser({
...currentUser,
user: user || null,
isVerified: user ? user.emailVerified : false,
email: user ? user.email : '',
accessToken: user ? user.Aa : '',
});
setLoading(false);
});
return unsubscribe;
}, []);
You'll need to manually refresh the token when it expires.
Store the token's expiry time somewhere. When you make an API call (assuming you're using axios), you can use a request interceptor to add the token. Just check if its expired first - if it is, fetch a new one using the refresh token and then make the API call. If it is not, just send the request.