Install firebase-auth-cloudflare-workers via npm
mainInstall the library from the npm registry to use zero-dependency Firebase authentication in your Cloudflare Workers.
$ npm i firebase-auth-cloudflare-workersrepository·main·Indexed 41 days ago
https://github.com/code-hex/firebase-auth-cloudflare-workersA zero-dependency Firebase Authentication library for Cloudflare Workers (v2.0.6). It enables verifying ID tokens and session cookies, managing custom user claims, and performing administrative tasks using Web Standard APIs. Includes built-in support for Cloudflare KV caching of public JWKs via WorkersKVStoreSingle and integration with the Firebase Auth Emulator.
Install the library from the npm registry to use zero-dependency Firebase authentication in your Cloudflare Workers.
$ npm i firebase-auth-cloudflare-workersIf a user has enrolled in second-factor authentication, the UserRecord.multiFactor property will contain a MultiFactorSettings object. This object contains an array of enrolledFactors.
if (user.multiFactor) {
user.multiFactor.enrolledFactors.forEach(factor => {
console.log(`Factor ID: ${factor.factorId}`); // 'phone' or 'totp'
console.log(`UID: ${factor.uid}`);
if (factor instanceof PhoneMultiFactorInfo) {
console.log(`Phone: ${factor.phoneNumber}`);
} else if (factor instanceof TotpMultiFactorInfo) {
console.log(`TOTP Info:`, factor.totpInfo);
}
});
}To use the Firebase Auth Emulator, ensure your wrangler.toml includes the FIREBASE_AUTH_EMULATOR_HOST variable. The SDK will automatically detect the emulator if the env object passed to API calls contains this host.
Example wrangler.toml configuration:
[vars]
FIREBASE_AUTH_EMULATOR_HOST = "127.0.0.1:9099"To avoid fetching the public key for every request, use WorkersKVStoreSingle.getOrInitialize() to implement the KeyStorer interface using Cloudflare KV. This caches the public key used to validate Firebase ID tokens.
cacheKey: The key used to store/retrieve the public key in KV.cfKVNamespace: The KVNamespace binding from your Cloudflare environment.const keyStore = WorkersKVStoreSingle.getOrInitialize(
env.PUBLIC_JWK_CACHE_KEY,
env.PUBLIC_JWK_CACHE_KV
);Use authObj.verifyIdToken() to validate a Firebase JWT. If valid, it returns a promise that resolves with the decoded FirebaseIdToken claims.
idToken: The JWT string to verify.checkRevoked: (Optional) If true, performs an extra request to the Firebase backend to check if the session was revoked.env: (Optional) Used to detect if the Firebase Auth Emulator should be used.const firebaseToken = await auth.verifyIdToken(jwt, false, env);Use authObj.verifySessionCookie() to validate a Firebase session cookie. It returns a promise with the cookie claims or rejects if the cookie is invalid.
sessionCookie: The cookie string to verify.checkRevoked: (Optional) If true, checks if the session was revoked via an extra backend request.env: (Optional) Used to detect if the Firebase Auth Emulator should be used.const firebaseToken = await auth.verifySessionCookie(sessionCookie, true, env);The Auth object provides several administrative methods:
getUser(uid, env): Fetches the UserRecord for a specific UID.revokeRefreshTokens(uid, env): Revokes all refresh tokens for a user.setCustomUserClaims(uid, customUserClaims, env): Sets custom claims on a user. Passing null deletes existing claims. Claims are added to the user's ID token. Note that claims larger than 1000 bytes will throw an error.// Set custom claims
await auth.setCustomUserClaims(uid, { role: 'admin' }, env);
// Get user
const user = await auth.getUser(uid, env);The Auth object is created as a singleton. This pattern is used because Cloudflare Module Workers only access environment variables during the request lifecycle.
To initialize the Auth instance, provide the projectId, a keyStore for caching public JWKs, and an optional credential (e.g., ServiceAccountCredential) if you need to perform Admin tasks like creating session cookies.
import { Auth, WorkersKVStoreSingle } from "firebase-auth-cloudflare-workers";
// Inside your fetch handler:
const auth = Auth.getOrInitialize(
env.PROJECT_ID,
WorkersKVStoreSingle.getOrInitialize(env.PUBLIC_JWK_CACHE_KEY, env.PUBLIC_JWK_CACHE_KV)
);Use authObj.createSessionCookie() to exchange an ID token for a session cookie. This is useful for server-side session management.
Note: This requires a service account credential to be provided during Auth.getOrInitialize().
idToken: The Firebase ID token to exchange.sessionCookieOptions: Options including custom session duration.env: (Optional) Used to detect if the Firebase Auth Emulator should be used.const sessionCookie = await auth.createSessionCookie(idToken, sessionCookieOptions, env);You can customize how the client handles failing HTTP requests using the RetryConfig interface. This allows you to control retries for specific HTTP status codes or low-level I/O errors, and define an exponential backoff strategy.
Key properties:
maxRetries: Maximum number of retry attempts.statusCodes: Array of HTTP status codes that trigger a retry (e.g., [503]).ioErrorCodes: Array of low-level I/O error codes to retry (e.g., ['ECONNRESET', 'ETIMEDOUT']).backOffFactor: Multiplier for exponential backoff. Delay is calculated as (2^n) * backOffFactor, where n is the number of retries. A factor of 0 means no delay; 1 means the duration doubles each iteration.maxDelayInMillis: The maximum time to wait before initiating a retry.export interface RetryConfig {
maxRetries: number;
statusCodes?: number[];
ioErrorCodes?: string[];
backOffFactor?: number;
maxDelayInMillis: number;
}The defaultRetryConfig() function provides a sensible default for HTTP requests. It is configured to retry up to 4 times on connection resets, timeouts, and HTTP 503 errors, using an exponential backoff factor of 0.5 and a maximum delay of 60 seconds.
const retryConfig = defaultRetryConfig();
// Returns:
// {
// maxRetries: 4,
// statusCodes: [503],
// ioErrorCodes: ['ECONNRESET', 'ETIMEDOUT'],
// backOffFactor: 0.5,
// maxDelayInMillis: 60000
// }The Auth class is a singleton used to verify Firebase ID tokens and session cookies. Use Auth.getOrInitialize() to obtain an instance. You must provide a projectId and a KeyStorer (such as WorkersKVStoreSingle). Optionally, you can provide a Credential (like ServiceAccountCredential) if you need to perform administrative tasks or if the library requires it for specific verification flows.
import { Auth, WorkersKVStoreSingle } from 'firebase-auth-cloudflare-workers';
// Assuming 'env.MY_KV' is a KVNamespace from Cloudflare
const keyStore = WorkersKVStoreSingle.getOrInitialize('firebase-jwks-cache', env.MY_KV);
const auth = Auth.getOrInitialize('your-firebase-project-id', keyStore);
// Example usage (method signatures from documentation):
// const decodedToken = await auth.verifyIdToken(idToken);