How to Fix Firebase Auth Token Expired
In this tutorial, you'll learn about How to Fix Firebase Auth Token Expired. We cover key concepts, practical examples, and best practices.
Firebase ID tokens expire after 1 hour. Your app returns "auth/id-token-expired" or API requests fail with 401 after the user has been logged in for a while.
The Wrong Way
// Forcing the user to log out and log back in
firebase.auth().signOut();
firebase.auth().signInWithEmailAndPassword(email, password);
This creates a poor user experience. Token refresh should be automatic.
The Right Way
Step 1: Use onAuthStateChanged for automatic refresh
firebase.auth().onAuthStateChanged(async (user) => {
if (user) {
// Firebase SDK refreshes tokens automatically
const token = await user.getIdToken(false);
// Use token for API requests
}
});
Step 2: Force token refresh when needed
// Before critical API calls, force refresh:
async function getValidToken() {
const user = firebase.auth().currentUser;
if (user) {
// true = force refresh even if not expired
return await user.getIdToken(true);
}
return null;
}
// Use in API interceptor:
api.interceptors.request.use(async (config) => {
config.headers.Authorization = `Bearer ${await getValidToken()}`;
return config;
});
Step 3: Handle token expiry on the server
// Backend: Verify token on every request
const admin = require('firebase-admin');
app.use(async (req, res, next) => {
const token = req.headers.authorization?.split('Bearer ')[1];
try {
// This verifies expiry automatically
const decoded = await admin.auth().verifyIdToken(token);
req.user = decoded;
next();
} catch (error) {
if (error.code === 'auth/id-token-expired') {
return res.status(401).json({ error: 'Token expired, refresh required' });
}
}
});
Step 4: Listen for token refresh
firebase.auth().onIdTokenChanged((user) => {
// Fired when the token is automatically refreshed
const newToken = user?.getIdToken();
console.log('Token refreshed');
});
Token refresh working — user stays logged in for 24+ hours without re-authentication.
Prevention
- Do not cache ID tokens on the client — always call
getIdToken()before API calls. - Set Firebase Auth session length in Firebase Console → Authentication → Settings → "Session duration."
- The token lifecycle management is standard in Doda Browser's authentication layer — automatic silent refresh prevents mid-session logouts.
Common Mistakes with auth token expired
- Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
These mistakes appear frequently in real-world FIREBASE code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro