MongoDB Adapter

Integrate Better Auth with MongoDB.

MongoDB is a popular NoSQL database that is widely used for building scalable and flexible applications. It provides a flexible schema that allows for easy data modeling and querying.

Before getting started, make sure you have MongoDB installed and configured. For more information, see MongoDB Documentation

Installation

To use the MongoDB adapter, you need to install the @better-auth/mongo-adapter package:

npm install @better-auth/mongo-adapter

Example Usage

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:

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, {
    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:

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.

Schema generation & migration

For MongoDB, we don't need to generate or migrate the schema.

Joins

Database joins are useful when Better-Auth needs to fetch related data from multiple tables in a single query. Endpoints like /get-session, /get-full-organization and many others benefit greatly from this feature, seeing upwards of 2x to 3x performance improvements depending on database latency.

The MongoDB adapter supports joins out of the box since version 1.4.0. To enable this feature, set advanced.database.joins to true in your auth configuration.

auth.ts
import { betterAuth } from "better-auth";

export const auth = betterAuth({
  advanced: {
    database: {
      joins: true,
    },
  },
});

Additional Information