MongoDB-backed authentication
Store Better Auth users, sessions, accounts, and verification data in MongoDB.
Better Auth · Const
mongodbAdapter configures Better Auth to use MongoDB as its database. Supply a MongoClient when the deployment supports transactions.
mongodbAdapter connects Better Auth to a MongoDB database object. Pass the MongoClient as an option when using a replica set or sharded cluster to enable transactions; standalone servers must omit that option because they do not support transactions.
mongodbAdapter(db, { client })| Name | Type | Description |
|---|---|---|
db | Db | MongoDB database instance returned by MongoClient.db(). |
options.client | MongoClient | Optional MongoClient used to enable transactions; use it with a replica set or sharded cluster. |
A Better Auth database adapter configured for MongoDB.
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, { client }),
});Creates a Better Auth instance backed by MongoDB and passes the client so transactions are enabled.
Store Better Auth users, sessions, accounts, and verification data in MongoDB.
Use atomic authentication writes on a MongoDB replica set or sharded cluster.
Use Better Auth's database joins for supported queries.
mongodbAdapter accepts a MongoDB database object and returns the database adapter used by Better Auth. The documented setup imports it from @better-auth/mongo-adapter and supplies the database returned by client.db().
Follow-up: How would you enable transactional operations? Pass the MongoClient through the adapter options, and use a replica set or sharded cluster rather than a standalone server.
Pass client when the MongoDB deployment supports transactions. The documentation recommends a connection string for a replica set or sharded cluster, while standalone MongoDB deployments require omitting client.
Follow-up: What failure behavior changes without transactions? Earlier writes can remain if a later write fails, so deployment topology affects atomicity.
MongoDB does not require Better Auth schema generation or migration. The adapter works with the existing database and does not use the schema-generation or migration workflow described for some other adapters.
Follow-up: What newer adapter capability is documented? Joins are supported out of the box from version 1.4.0 when advanced.database.joins is enabled.
betterAuthMongoClient@better-auth/mongo-adapteradvanced.database.joins