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.
Code
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');Report a problem with this exampleOpens a pre-filled issue on GitHub.