Firestore Adapter for Better Auth

1.2.2 · active · verified Wed Apr 22

The `better-auth-firestore` package provides a robust Firestore adapter for the `Better Auth` authentication library, utilizing the Firebase Admin SDK. Currently at stable version `1.2.2`, it receives frequent updates, with several patch and minor releases in the past few months addressing bugs and adding features. This library acts as a drop-in replacement for `Auth.js` (formerly `NextAuth.js`) Firebase adapter, maintaining a compatible data shape, which simplifies migrations. Its key differentiators include built-in handling for Firestore-specific limitations, such as chunking `IN` queries that exceed the 30-value cap, and providing helper functions like `initFirestore` for easy setup and `generateIndexSetupUrl` for required index creation. It strictly targets Node.js 22+ and is designed for TypeScript projects, shipping with full type definitions. While it handles Firestore data storage, `better-auth-firebase-auth` is recommended for actual Firebase Authentication provider integration.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the Firestore adapter with `better-auth` using Firebase Admin SDK credentials, enabling session and user data persistence in Firestore.

import { betterAuth } from "better-auth";
import { firestoreAdapter, initFirestore } from "better-auth-firestore";
import { cert } from "firebase-admin/app";
import { getFirestore } from "firebase-admin/firestore"; // Also useful for direct Firestore access

// Initialize Firebase Admin SDK for Firestore.
// Ensure these environment variables are securely managed in production.
const firestore = initFirestore({
	credential: cert({
		projectId: process.env.FIREBASE_PROJECT_ID ?? '',
		clientEmail: process.env.FIREBASE_CLIENT_EMAIL ?? '',
		privateKey: (process.env.FIREBASE_PRIVATE_KEY ?? '').replace(/\\n/g, "\n"),
	}),
	projectId: process.env.FIREBASE_PROJECT_ID ?? '',
	name: "better-auth" // Optional: name for the Firebase App instance
});

// Configure Better Auth with the Firestore adapter.
export const auth = betterAuth({
	// Additional Better Auth configuration options would go here,
	// e.g., providers, callbacks, etc.
	secret: process.env.AUTH_SECRET ?? 'super-secret-key-for-development-only', // Required for Better Auth
	database: firestoreAdapter({
		firestore,
		// Optional: Customize collection names if needed.
		// These are the default values if not specified:
		collections: {
			users: "users",
			sessions: "sessions",
			accounts: "accounts",
			verificationTokens: "verificationTokens"
		},
		// Optional: Define a naming strategy for fields (e.g., 'default' or 'snake_case')
		namingStrategy: "default"
	})
});

// Example of how to access the initialized auth instance (e.g., in an API route)
async function getUserSession(sessionId: string) {
    // In a real application, you would use `auth.getSession()` or similar
    // This is just to demonstrate the `auth` object is available.
    // const session = await auth.getSession({ req: someRequest });
    // console.log("Session:", session);
    console.log(`Auth instance initialized with Firestore adapter and sessionId: ${sessionId}`);
    // You can also directly interact with Firestore via the 'firestore' object
    const userDoc = await firestore.collection('users').doc('someUserId').get();
    if (userDoc.exists) {
        console.log("Example user data:", userDoc.data());
    }
}

// Call the example function (for demonstration purposes, not part of actual quickstart)
getUserSession('example-session-id-123');

view raw JSON →