Skip to content

How to Fix Firebase Auth Token Expired

DodaTech Updated 2026-06-24 3 min read

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

  1. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
  2. Using return to exit a function early instead of wrapping a pure value in the monad
  3. 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

### How long do Firebase ID tokens last?

Firebase ID tokens expire after 1 hour. Firebase SDK automatically refreshes them using the refresh token (which lasts until revoked). The refresh happens in the background without user intervention.

Why does my Firebase token still work after 1 hour?

The Firebase SDK refreshes the ID token before it expires. The onIdTokenChanged callback fires when the new token is issued. If getIdToken(false) is called, it returns the cached token (possibly near expiry). Use getIdToken(true) to force a refresh.

Can I extend the Firebase ID token lifetime?

No. Firebase ID tokens are hard-coded at 1 hour. You cannot extend this. However, you can set custom session duration for the refresh token (up to 2 weeks for sensitive data, unlimited for non-sensitive).

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro