MongoDB Adapter Initialization Error During Sign-In - Better-Auth v1.3.13 #1990

Closed
opened 2026-03-13 09:19:22 -05:00 by GiteaMirror · 1 comment
Owner

Originally created by @Tellisense on GitHub (Sep 21, 2025).

Is this suited for github?

  • Yes, this is suited for github

To Reproduce

To Reproduce

  1. Set up a Next.js 15 app with
    Better-Auth and MongoDB adapter:

// src/lib/better-auth/auth.ts
import { betterAuth } from 'better-auth';
import { mongodbAdapter } from
'better-auth/adapters/mongodb';
import { MongoClient } from 'mongodb';

const client = new
MongoClient(process.env.MONGODB_URI!);
await client.connect();
const db = client.db();

export const auth = betterAuth({
database: mongodbAdapter(db),
emailAndPassword: {
enabled: true,
requireEmailVerification: false,
},
session: {
expiresIn: 60 * 60 * 8,
updateAge: 60 * 60,
},
});

  1. Create the API route handler:

// src/app/api/auth/[...all]/route.ts
import { auth } from
'@/lib/better-auth/auth';
import { toNextJsHandler } from
'better-auth/next-js';

const handlers = toNextJsHandler(auth);

export const { GET, POST } = handlers;

  1. Register a new user (this works):

curl -X POST http://localhost:3000/api/aut
h/sign-up/email
-H "Content-Type: application/json"
-d '{"email":"test@example.com","passwor
d":"Password123","name":"Test User"}'

Response: 200 OK

{"token":"...","user":{"id":"...","email

":"test@example.com",...}}

  1. Attempt to sign in with the registered
    user (this fails):

curl -X POST http://localhost:3000/api/aut
h/sign-in/email
-H "Content-Type: application/json"
-d '{"email":"test@example.com","passwor
d":"Password123"}'

Response: 500 Internal Server Error

Console error: "Failed to initialize

database adapter"

  1. Verify the database state:
    - user collection: User document exists
    with correct data
    - account collection: Password hash
    stored correctly (BCrypt format)
    - session collection: No session created
    due to the error

Expected behavior: Sign-in should succeed
and create a session after password
verification.

Actual behavior: Sign-in fails with
"Failed to initialize database adapter"
error, even though password verification
succeeds (verified through debug logs).

Additional context:
The error occurs specifically during the
session creation phase after successful
password verification. Registration works
perfectly, suggesting the adapter
initialization issue only affects certain
operations.

Current vs. Expected behavior

Reproduction:

// Setup
const auth = betterAuth({
database: mongodbAdapter(db), // MongoDB connection works
emailAndPassword: { enabled: true }
});

// Sign-up works: POST /api/auth/sign-up/email
// Sign-in fails: POST /api/auth/sign-in/email

Observations:

  • What's Working:
  • The MongoDB connection is established successfully.
  • User registration successfully creates user and account documents.
  • Password verification succeeds (BCrypt comparison returns true).
  • What Fails:
  • Session creation appears to trigger the adapter initialization error.
  • The error occurs after password verification but before a session can be created.

Database Collections:

  • user collection: Documents are created successfully.
  • account collection: Password hashes are stored correctly.
  • session collection: This collection exists, but sessions are not created in it due to the error.

It seems the adapter might be losing its initialization state between the successful registration process and the failing sign-in process. This could be related to how the MongoDB adapter manages the database instance across different operations.

Any guidance or potential fixes would be greatly appreciated. I am happy to provide more debugging information if needed.

What version of Better Auth are you using?

better-auth@1.3.13

System info

{
  "system": {
    "platform": "darwin",
    "arch": "arm64",
    "version": "Darwin Kernel Version 24.6.0: Mon Jul 14 11:30:40 PDT 2025; root:xnu-11417.140.69~1/RELEASE_ARM64_T6041",
    "release": "24.6.0",
    "cpuCount": 14,
    "cpuModel": "Apple M4 Pro",
    "totalMemory": "48.00 GB",
    "freeMemory": "0.62 GB"
  },
  "node": {
    "version": "v22.19.0",
    "env": "development"
  },
  "packageManager": {
    "name": "npm",
    "version": "10.9.3"
  },
  "frameworks": [
    {
      "name": "next",
      "version": "15.5.2"
    },
    {
      "name": "react",
      "version": "19.1.1"
    }
  ],
  "databases": [
    {
      "name": "mongodb",
      "version": "^6.20.0"
    }
  ],
  "betterAuth": {
    "version": "^1.3.13",
    "config": null
  }
}

Which area(s) are affected? (Select all that apply)

Backend, Package

Auth config (if applicable)

import { betterAuth } from "better-auth"
export const auth = betterAuth({
  emailAndPassword: {  
    enabled: true
  },
});

Additional context

No response

Originally created by @Tellisense on GitHub (Sep 21, 2025). ### Is this suited for github? - [x] Yes, this is suited for github ### To Reproduce To Reproduce 1. Set up a Next.js 15 app with Better-Auth and MongoDB adapter: // src/lib/better-auth/auth.ts import { betterAuth } from 'better-auth'; import { mongodbAdapter } from 'better-auth/adapters/mongodb'; import { MongoClient } from 'mongodb'; const client = new MongoClient(process.env.MONGODB_URI!); await client.connect(); const db = client.db(); export const auth = betterAuth({ database: mongodbAdapter(db), emailAndPassword: { enabled: true, requireEmailVerification: false, }, session: { expiresIn: 60 * 60 * 8, updateAge: 60 * 60, }, }); 2. Create the API route handler: // src/app/api/auth/[...all]/route.ts import { auth } from '@/lib/better-auth/auth'; import { toNextJsHandler } from 'better-auth/next-js'; const handlers = toNextJsHandler(auth); export const { GET, POST } = handlers; 3. Register a new user (this works): curl -X POST http://localhost:3000/api/aut h/sign-up/email \ -H "Content-Type: application/json" \ -d '{"email":"test@example.com","passwor d":"Password123","name":"Test User"}' # Response: 200 OK # {"token":"...","user":{"id":"...","email ":"test@example.com",...}} 4. Attempt to sign in with the registered user (this fails): curl -X POST http://localhost:3000/api/aut h/sign-in/email \ -H "Content-Type: application/json" \ -d '{"email":"test@example.com","passwor d":"Password123"}' # Response: 500 Internal Server Error # Console error: "Failed to initialize database adapter" 5. Verify the database state: - user collection: User document exists with correct data - account collection: Password hash stored correctly (BCrypt format) - session collection: No session created due to the error Expected behavior: Sign-in should succeed and create a session after password verification. Actual behavior: Sign-in fails with "Failed to initialize database adapter" error, even though password verification succeeds (verified through debug logs). Additional context: The error occurs specifically during the session creation phase after successful password verification. Registration works perfectly, suggesting the adapter initialization issue only affects certain operations. ### Current vs. Expected behavior **Reproduction:** ```javascript // Setup const auth = betterAuth({ database: mongodbAdapter(db), // MongoDB connection works emailAndPassword: { enabled: true } }); // Sign-up works: POST /api/auth/sign-up/email // Sign-in fails: POST /api/auth/sign-in/email ``` **Observations:** * **What's Working:** * The MongoDB connection is established successfully. * User registration successfully creates user and account documents. * Password verification succeeds (BCrypt comparison returns true). * **What Fails:** * Session creation appears to trigger the adapter initialization error. * The error occurs after password verification but before a session can be created. **Database Collections:** * `user` collection: Documents are created successfully. * `account` collection: Password hashes are stored correctly. * `session` collection: This collection exists, but sessions are not created in it due to the error. It seems the adapter might be losing its initialization state between the successful registration process and the failing sign-in process. This could be related to how the MongoDB adapter manages the database instance across different operations. Any guidance or potential fixes would be greatly appreciated. I am happy to provide more debugging information if needed. ### What version of Better Auth are you using? better-auth@1.3.13 ### System info ```bash { "system": { "platform": "darwin", "arch": "arm64", "version": "Darwin Kernel Version 24.6.0: Mon Jul 14 11:30:40 PDT 2025; root:xnu-11417.140.69~1/RELEASE_ARM64_T6041", "release": "24.6.0", "cpuCount": 14, "cpuModel": "Apple M4 Pro", "totalMemory": "48.00 GB", "freeMemory": "0.62 GB" }, "node": { "version": "v22.19.0", "env": "development" }, "packageManager": { "name": "npm", "version": "10.9.3" }, "frameworks": [ { "name": "next", "version": "15.5.2" }, { "name": "react", "version": "19.1.1" } ], "databases": [ { "name": "mongodb", "version": "^6.20.0" } ], "betterAuth": { "version": "^1.3.13", "config": null } } ``` ### Which area(s) are affected? (Select all that apply) Backend, Package ### Auth config (if applicable) ```typescript import { betterAuth } from "better-auth" export const auth = betterAuth({ emailAndPassword: { enabled: true }, }); ``` ### Additional context _No response_
GiteaMirror added the adapterbug labels 2026-03-13 09:19:22 -05:00
Author
Owner

@dosubot[bot] commented on GitHub (Sep 21, 2025):

Hi @Tellisense! I'm Dosu and I’m helping the better-auth team.

The error is caused by the MongoDB adapter not being initialized with both the database and the MongoClient instance. In Better Auth v1.3.13+, the recommended pattern is to use mongodbAdapter(db, { client }) instead of just mongodbAdapter(db). This change ensures the adapter maintains its state correctly and supports session creation, especially in environments like Next.js where handlers may be re-initialized per request. Update your initialization to:

const client = new MongoClient(process.env.MONGODB_URI!);
await client.connect();
const db = client.db();

export const auth = betterAuth({
  database: mongodbAdapter(db, { client }),
  // ...rest of your config
});

This should resolve the "Failed to initialize database adapter" error during sign-in and session creation. If you still see issues, double-check that both db and client are valid and stable across requests. For reference, see the adapter initialization update and recent refactor.

To reply, just mention @dosu.


How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other  Chat with Dosu Join Discord Share on X

@dosubot[bot] commented on GitHub (Sep 21, 2025): <!-- Greeting --> Hi @Tellisense! I'm [Dosu](https://go.dosu.dev/dosubot) and I’m helping the better-auth team. <!-- Answer --> The error is caused by the MongoDB adapter not being initialized with both the database and the MongoClient instance. In Better Auth v1.3.13+, the recommended pattern is to use `mongodbAdapter(db, { client })` instead of just `mongodbAdapter(db)`. This change ensures the adapter maintains its state correctly and supports session creation, especially in environments like Next.js where handlers may be re-initialized per request. Update your initialization to: ```ts const client = new MongoClient(process.env.MONGODB_URI!); await client.connect(); const db = client.db(); export const auth = betterAuth({ database: mongodbAdapter(db, { client }), // ...rest of your config }); ``` This should resolve the "Failed to initialize database adapter" error during sign-in and session creation. If you still see issues, double-check that both `db` and `client` are valid and stable across requests. For reference, see the [adapter initialization update](https://github.com/better-auth/better-auth/pull/4532) and [recent refactor](https://github.com/better-auth/better-auth/pull/4676). <!-- Dosu Comment Footer --> *To reply, just mention [@dosu](https://go.dosu.dev/dosubot).* --- <sup>How did I do? [Good](https://app.dosu.dev/response-feedback/6e6feead-ee19-4e80-83a1-c434db1cbed5?feedback_type=great_response) | [Irrelevant](https://app.dosu.dev/response-feedback/6e6feead-ee19-4e80-83a1-c434db1cbed5?feedback_type=irrelevant_answer) | [Incorrect](https://app.dosu.dev/response-feedback/6e6feead-ee19-4e80-83a1-c434db1cbed5?feedback_type=incorrect_sources) | [Verbose](https://app.dosu.dev/response-feedback/6e6feead-ee19-4e80-83a1-c434db1cbed5?feedback_type=too_verbose) | [Hallucination](https://app.dosu.dev/response-feedback/6e6feead-ee19-4e80-83a1-c434db1cbed5?feedback_type=hallucination) | [Report 🐛](https://app.dosu.dev/response-feedback/6e6feead-ee19-4e80-83a1-c434db1cbed5?feedback_type=bug_report) | [Other](https://app.dosu.dev/response-feedback/6e6feead-ee19-4e80-83a1-c434db1cbed5?feedback_type=other)</sup>&nbsp;&nbsp;[![Chat with Dosu](https://dosu.dev/dosu-chat-badge.svg)](https://app.dosu.dev/cdda13d9-dd27-4d31-b09a-5d8bec92de21/ask?utm_source=github)&nbsp;[![Join Discord](https://img.shields.io/badge/join-5865F2?logo=discord&logoColor=white&label=)](https://go.dosu.dev/discord-bot)&nbsp;[![Share on X](https://img.shields.io/badge/X-share-black)](https://twitter.com/intent/tweet?text=%40dosu_ai%20helped%20me%20solve%20this%20issue!&url=https%3A//github.com/better-auth/better-auth/issues/4802)
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: github-starred/better-auth#1990