From 733f7934a1dded05719451de7c8edba42eaf3205 Mon Sep 17 00:00:00 2001 From: Taesu <166604494+bytaesu@users.noreply.github.com> Date: Sat, 3 Oct 2026 10:07:35 +0900 Subject: [PATCH] docs(mongo-adapter): clarify transaction setup (#11550) --- docs/content/docs/adapters/mongo.mdx | 28 ++++++++++++++++++++++++---- docs/content/docs/installation.mdx | 5 ++++- 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/docs/content/docs/adapters/mongo.mdx b/docs/content/docs/adapters/mongo.mdx index 3020aee85e..a108e6d04e 100644 --- a/docs/content/docs/adapters/mongo.mdx +++ b/docs/content/docs/adapters/mongo.mdx @@ -19,24 +19,44 @@ To use the MongoDB adapter, you need to install the `@better-auth/mongo-adapter` ## Example Usage -You can use the MongoDB adapter to connect to your database as follows. +### Replica set or sharded cluster + +Pass `client` so the adapter uses transactions by default. Use a connection string for your replica set or sharded cluster: ```ts title="auth.ts" import { betterAuth } from "better-auth"; import { MongoClient } from "mongodb"; -import { mongodbAdapter } from "better-auth/adapters/mongodb"; +import { mongodbAdapter } from "@better-auth/mongo-adapter"; const client = new MongoClient("mongodb://localhost:27017/database"); const db = client.db(); export const auth = betterAuth({ database: mongodbAdapter(db, { - // Optional: if you don't provide a client, database transactions won't be enabled. - client + client, }), }); ``` +### Standalone server + +A standalone MongoDB server does not support transactions. Create `db` with `MongoClient` and pass it to the adapter without the `client` option: + +```ts title="auth.ts" +import { betterAuth } from "better-auth"; +import { MongoClient } from "mongodb"; +import { mongodbAdapter } from "@better-auth/mongo-adapter"; + +const client = new MongoClient("mongodb://localhost:27017/database"); +const db = client.db(); + +export const auth = betterAuth({ + database: mongodbAdapter(db), +}); +``` + +Without transactions, an earlier write may remain if a later write fails. When you move to a replica set or sharded cluster, pass `client` to enable transactions. See [MongoDB's transaction requirements](https://www.mongodb.com/docs/manual/core/transactions-production-consideration/#availability). + ## Schema generation & migration For MongoDB, we don't need to generate or migrate the schema. diff --git a/docs/content/docs/installation.mdx b/docs/content/docs/installation.mdx index 897842a8f5..b181948c97 100644 --- a/docs/content/docs/installation.mdx +++ b/docs/content/docs/installation.mdx @@ -157,9 +157,12 @@ description: Learn how to configure Better Auth in your project. import { client } from "@/db"; // your mongodb client export const auth = betterAuth({ - database: mongodbAdapter(client), + database: mongodbAdapter(client.db(), { client }), }); ``` + + See the [MongoDB adapter guide](/docs/adapters/mongo) for standalone + server setup.