{"id":16715,"library":"better-auth-firestore","title":"Firestore Adapter for Better Auth","description":"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.","status":"active","version":"1.2.2","language":"javascript","source_language":"en","source_url":"https://github.com/yultyyev/better-auth-firestore","tags":["javascript","better-auth","firebase","firestore","adapter","authjs","nextauth","oauth","session","typescript"],"install":[{"cmd":"npm install better-auth-firestore","lang":"bash","label":"npm"},{"cmd":"yarn add better-auth-firestore","lang":"bash","label":"yarn"},{"cmd":"pnpm add better-auth-firestore","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core dependency; provides the Better Auth framework this adapter integrates with.","package":"better-auth","optional":false},{"reason":"Required for interacting with Firestore via the Firebase Admin SDK.","package":"firebase-admin","optional":false},{"reason":"Package ships with types and is primarily used in TypeScript projects.","package":"typescript","optional":false}],"imports":[{"note":"This package is ESM-only, requiring Node.js 22+. CommonJS `require()` is not supported.","wrong":"const firestoreAdapter = require('better-auth-firestore');","symbol":"firestoreAdapter","correct":"import { firestoreAdapter } from 'better-auth-firestore';"},{"note":"A named export for convenient Firebase Admin SDK initialization, not a default export.","wrong":"import initFirestore from 'better-auth-firestore';","symbol":"initFirestore","correct":"import { initFirestore } from 'better-auth-firestore';"},{"note":"Utility function to generate a Firebase Console URL for creating required Firestore indexes.","wrong":null,"symbol":"generateIndexSetupUrl","correct":"import { generateIndexSetupUrl } from 'better-auth-firestore';"}],"quickstart":{"code":"import { betterAuth } from \"better-auth\";\nimport { firestoreAdapter, initFirestore } from \"better-auth-firestore\";\nimport { cert } from \"firebase-admin/app\";\nimport { getFirestore } from \"firebase-admin/firestore\"; // Also useful for direct Firestore access\n\n// Initialize Firebase Admin SDK for Firestore.\n// Ensure these environment variables are securely managed in production.\nconst firestore = initFirestore({\n\tcredential: cert({\n\t\tprojectId: process.env.FIREBASE_PROJECT_ID ?? '',\n\t\tclientEmail: process.env.FIREBASE_CLIENT_EMAIL ?? '',\n\t\tprivateKey: (process.env.FIREBASE_PRIVATE_KEY ?? '').replace(/\\\\n/g, \"\\n\"),\n\t}),\n\tprojectId: process.env.FIREBASE_PROJECT_ID ?? '',\n\tname: \"better-auth\" // Optional: name for the Firebase App instance\n});\n\n// Configure Better Auth with the Firestore adapter.\nexport const auth = betterAuth({\n\t// Additional Better Auth configuration options would go here,\n\t// e.g., providers, callbacks, etc.\n\tsecret: process.env.AUTH_SECRET ?? 'super-secret-key-for-development-only', // Required for Better Auth\n\tdatabase: firestoreAdapter({\n\t\tfirestore,\n\t\t// Optional: Customize collection names if needed.\n\t\t// These are the default values if not specified:\n\t\tcollections: {\n\t\t\tusers: \"users\",\n\t\t\tsessions: \"sessions\",\n\t\t\taccounts: \"accounts\",\n\t\t\tverificationTokens: \"verificationTokens\"\n\t\t},\n\t\t// Optional: Define a naming strategy for fields (e.g., 'default' or 'snake_case')\n\t\tnamingStrategy: \"default\"\n\t})\n});\n\n// Example of how to access the initialized auth instance (e.g., in an API route)\nasync function getUserSession(sessionId: string) {\n    // In a real application, you would use `auth.getSession()` or similar\n    // This is just to demonstrate the `auth` object is available.\n    // const session = await auth.getSession({ req: someRequest });\n    // console.log(\"Session:\", session);\n    console.log(`Auth instance initialized with Firestore adapter and sessionId: ${sessionId}`);\n    // You can also directly interact with Firestore via the 'firestore' object\n    const userDoc = await firestore.collection('users').doc('someUserId').get();\n    if (userDoc.exists) {\n        console.log(\"Example user data:\", userDoc.data());\n    }\n}\n\n// Call the example function (for demonstration purposes, not part of actual quickstart)\ngetUserSession('example-session-id-123');","lang":"typescript","description":"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."},"warnings":[{"fix":"Update your package dependencies and imports from `@yultyyev/better-auth-firestore` to `better-auth-firestore`. Run `npm uninstall @yultyyev/better-auth-firestore && npm install better-auth-firestore`.","message":"The package moved from `@yultyyev/better-auth-firestore` to an unscoped name `better-auth-firestore`. Users of the scoped package must migrate to the new name.","severity":"breaking","affected_versions":"<1.1.1"},{"fix":"Upgrade to `better-auth-firestore@1.2.0` or later to automatically handle `IN` query chunking. If unable to upgrade, ensure your queries against the adapter do not exceed 30 values in a single `IN` clause.","message":"Firestore `IN` queries have a hard limit of 30 values. Prior to `v1.2.0`, queries exceeding this limit would fail. The adapter now chunks these queries automatically.","severity":"gotcha","affected_versions":"<1.2.0"},{"fix":"Ensure your project runs on Node.js version 22 or higher and is configured for ES Modules. If migrating from CommonJS, update your `package.json` with `\"type\": \"module\"` and adjust import/export statements.","message":"This package is ESM-only and requires Node.js 22+ as specified in its `engines` field. Older Node.js versions or CommonJS environments are not supported.","severity":"gotcha","affected_versions":"*"},{"fix":"Upgrade to `better-auth-firestore@1.1.4` or later to ensure proper `.js` extension handling for ESM compatibility.","message":"Node.js ESM compatibility requires explicit `.js` extensions for relative imports. Versions prior to `v1.1.4` might encounter module resolution errors in certain ESM configurations.","severity":"gotcha","affected_versions":"<1.1.4"},{"fix":"Use the `generateIndexSetupUrl` helper from `better-auth-firestore` to get a direct link to create the index in the Firebase Console, or create it manually: Collection ID `verificationTokens`, Fields: `token` (Ascending), `expires` (Ascending).","message":"A composite Firestore index on the `verification` collection is required for proper functionality. Without it, operations involving verification tokens will fail.","severity":"gotcha","affected_versions":"*"},{"fix":"Always keep `better-auth-firestore` and `better-auth` updated to their latest compatible versions. If experiencing unexpected behavior, check the release notes for both packages for specific compatibility requirements.","message":"Compatibility with `better-auth` versions is important. `better-auth-firestore@1.1.3` introduced explicit support for `better-auth@1.5`, and future `better-auth` major versions may require corresponding `better-auth-firestore` updates.","severity":"gotcha","affected_versions":"<1.1.3"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Refactor your code to use ES Modules `import` syntax for `better-auth-firestore` and ensure your `package.json` specifies `\"type\": \"module\"` if running in Node.js ESM.","cause":"Attempting to use CommonJS `require()` in an ES Modules (ESM) environment where only `import` statements are supported.","error":"ReferenceError: require is not defined"},{"fix":"Upgrade `better-auth-firestore` to `v1.1.4` or later, which includes fixes for ESM compatibility by adding `.js` extensions to relative imports.","cause":"Node.js ESM resolution failed to find a relative module, often due to missing `.js` extensions in import paths in older versions of the library.","error":"ERR_MODULE_NOT_FOUND: Cannot find module './some-module' resolved with .js extension"},{"fix":"Upgrade `better-auth-firestore` to `v1.2.0` or later. This version introduces automatic chunking of `IN` queries to work around this limitation.","cause":"A Firestore query generated by the adapter exceeded the 30-value limit for `IN` clauses.","error":"FirebaseError: The query uses an 'in' or 'array-contains-any' clause with more than 30 values. Make sure your 'in' or 'array-contains-any' queries do not exceed this limit."},{"fix":"Follow the provided link in the error message, or use `generateIndexSetupUrl` from the package to create the required index through the Firebase Console. Alternatively, create it manually via `verificationTokens` collection, `token` (Ascending), `expires` (Ascending).","cause":"The necessary composite index for the `verificationTokens` collection (on `token` and `expires`) has not been created in your Firestore database.","error":"FirebaseError: A required index is missing or out of date. You can create it with the following link: [link to Firebase Console]"}],"ecosystem":"npm"}