Skip to main content
MongoDB is a document-oriented NoSQL database. Better Auth provides a first-class MongoDB adapter that maps auth collections to MongoDB documents.

Installation

1

Install the MongoDB driver

2

Configure the adapter

Import mongodbAdapter from better-auth/adapters/mongodb. Pass a Db instance and, optionally, the MongoClient to enable transactions:
auth.ts

Configuration options

The mongodbAdapter function accepts a Db instance and an optional config object:
Transactions require a MongoDB replica set. If you are running a standalone MongoDB server without a replica set, you must set transaction: false explicitly.

Schema and migrations

MongoDB is schemaless — Better Auth creates collections automatically as data is written. There is no generate or migrate step required.
Better Auth uses the following collection names by default: user, session, account, and verification. Collection names match the model names defined in your auth config.

Indexes

MongoDB does not enforce uniqueness or index constraints automatically. For optimal performance and data integrity, create the following indexes:
Use the TTL index on session.expiresAt to have MongoDB automatically remove expired sessions without a background job.

Experimental joins

Enabling joins allows Better Auth to use MongoDB $lookup aggregations to fetch related data in a single query instead of multiple round-trips.
auth.ts