Firebase Auth for Cloudflare Workers

0.4.0 · active · verified Wed Apr 22

Cloudfire Auth is a JavaScript/TypeScript library designed to integrate Firebase Authentication functionalities directly within Cloudflare Workers environments. Currently at version 0.4.0, it provides core features such as Firebase ID token verification, user retrieval, and user deletion. The library leverages native Cloudflare APIs, specifically Cloudflare KV, for efficient OAuth2 token caching, which is crucial for performance and cost-effectiveness in a serverless context. It is built with a strong emphasis on modern JavaScript, being ESM-only, and offers full TypeScript support, making it suitable for contemporary development workflows. Key differentiators include its tight integration with Cloudflare's ecosystem, minimal external dependencies (only 'jose' for JWT handling), and its focus on solving the specific challenge of running Firebase Auth in a Worker environment where the official Firebase Admin SDK is not directly compatible due to Node.js-specific dependencies.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `CloudFireAuth` in a Cloudflare Worker, load service account credentials from environment variables, and verify a Firebase ID token from an incoming request's Authorization header.

import { CloudFireAuth } from "cloudfire-auth";

interface Env {
  YOUR_KV_NAMESPACE?: KVNamespace;
  FIREBASE_PRIVATE_KEY: string;
  FIREBASE_CLIENT_EMAIL: string;
  // ... other service account fields as environment variables
}

export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
    // It is best practice to store your service account key separately and
    // load it from a secure source, e.g., environment variables.
    const serviceAccountKey = {
      private_key: env.FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n'), // Handle newline characters if from env
      client_email: env.FIREBASE_CLIENT_EMAIL,
      // Add other necessary fields from your Firebase service account key
      // For example, project_id, type, private_key_id, etc.
      // Ensure the structure matches ServiceAccountKey type.
    };

    // Initialize with your Firebase project credentials
    const auth = new CloudFireAuth(
      serviceAccountKey,
      env.YOUR_KV_NAMESPACE // Optional: KV namespace for token caching
    );

    const idToken = request.headers.get('Authorization')?.split('Bearer ')[1];

    if (!idToken) {
      return new Response('No ID token provided', { status: 401 });
    }

    // Verify an ID token
    try {
      const decodedToken = await auth.verifyIdToken(idToken);
      console.log("User ID:", decodedToken.uid);
      return new Response(`Verified user: ${decodedToken.uid}`, { status: 200 });
    } catch (error: any) {
      console.error("Token verification failed:", error.message);
      return new Response(`Token verification failed: ${error.message}`, { status: 401 });
    }
  },
};

view raw JSON →