Firebase Auth Session Token Refresh

Subscribe to Firebase auth state, read the current ID token before each API call, and let the SDK refresh expired tokens transparently.

JavascriptAuth Jwt

Code

javascriptsnippet
38 lines
import { initializeApp } from 'firebase/app';
import {
  getAuth, onAuthStateChanged, signInAnonymously,
} from 'firebase/auth';

const app = initializeApp({
  apiKey: process.env.FIREBASE_API_KEY,
  authDomain: 'demo.firebaseapp.com',
  projectId: 'demo-project',
});

const auth = getAuth(app);

onAuthStateChanged(auth, (user) => {
  if (user) {
    console.log('signed in as', user.uid, 'anonymous:', user.isAnonymous);
  } else {
    console.log('signed out');
  }
});

await signInAnonymously(auth);

async function authorizedFetch(path) {
  const user = auth.currentUser;
  if (!user) throw new Error('auth required');

  // getToken 强制刷新已过期的 ID 令牌,保持短期凭证语义
  const token = await user.getIdToken(true);
  const res = await fetch('https://api.example.com' + path, {
    headers: { Authorization: 'Bearer ' + token },
  });
  if (res.status === 401) throw new Error('token rejected upstream');
  return res.json();
}

const profile = await authorizedFetch('/me');
console.log('profile loaded:', Object.keys(profile).length, 'fields');

How it works

Count the function authorizedFetch as the entire surface area of Firebase Auth Session Token Refresh.

The async parts await their results, which keeps ordering predictable. From firebase/app it pulls initializeApp, getAuth, onAuthStateChanged, signInAnonymously — the imports name exactly which library surface the snippet touches. When the guard condition holds, Error is thrown rather than a bogus value returned.

The code reads FIREBASE_API_KEY from the environment at startup.

What to watch for

  • Dependency check: firebase/app and firebase/auth — not built-in, must be present in the project.
  • This is browser-side code — fetch will not resolve in Node.
  • The guard !user short-circuits the flow with an early throw when its condition holds.

Using it

The main signature reads async function authorizedFetch(path)

The demo output is labeled (signed in as, signed out, profile loaded:), so every printed line maps back to its originating operation.

Key statements

if (res.status === 401) throw new Error('token rejected upstream');
const res = await fetch('https://api.example.com' + path, {
headers: { Authorization: 'Bearer ' + token },
});
const profile = await authorizedFetch('/me');

Interactive Tools for This Topic

FAQ

What does the snippet do with malformed data?
It throws `Error` before any real work runs, via the guard `!user` — handle it at the call site or let it propagate deliberately.
Does this require external packages?
Yes — `firebase/app` and `firebase/auth`. Add them to your project before running the snippet.