MongoDB-backed authentication
An Auth.js application needs users, accounts, sessions, or verification data persisted in MongoDB.
Auth.js · Const
MongoDBAdapter connects Auth.js to MongoDB by turning a MongoDB client source into an Auth.js Adapter. It supports direct clients and custom client factories, with optional connection-close handling.
MongoDBAdapter accepts a MongoDB client source and returns an Auth.js Adapter. The client may be a MongoClient, a promise, or a function; the function form supports custom connection management together with onClose.
function MongoDBAdapter(client, options): Adapter| Name | Type | Description |
|---|---|---|
client | MongoClient | Promise<MongoClient> | () => MongoClient | Promise<MongoClient> | MongoDB client, a promise resolving to a MongoClient, or a function returning either form. |
options | object | Adapter options, including optional onClose connection-cleanup behavior. |
Adapter
import NextAuth from "next-auth"
import { MongoDBAdapter } from "@auth/mongodb-adapter"
import client from "./lib/db"
export const { handlers, auth } = NextAuth({
adapter: MongoDBAdapter(client),
providers: [],
})Pass a MongoClient to MongoDBAdapter, then assign the resulting adapter to Auth.js configuration.
An Auth.js application needs users, accounts, sessions, or verification data persisted in MongoDB.
An application must control when and how MongoDB connections are created or reused.
A deployment needs explicit cleanup for a MongoDB client.
MongoDBAdapter is the official MongoDB adapter for Auth.js. It receives a MongoDB client source and produces an Adapter that Auth.js can use for database-backed authentication data.
Follow-up: What client forms can it accept? A MongoClient, a promise resolving to one, or a function returning one; the function form is useful for custom connection strategies.
Pass the returned adapter through Auth.js configuration using the adapter option. The usual form is MongoDBAdapter(client), where client is imported from the application's database module.
Follow-up: Why might the client be supplied as a function? It enables more customized connection behavior, especially when paired with the onClose option.
The adapter does not manage connections automatically, so the supplied MongoClient must be handled by the application. The documented recommendation is to provide a non-connected MongoClient instance.
Follow-up: When is a promise acceptable? It can resolve to a connected MongoClient, but the documentation marks that approach as not recommended because connection failures can cause unhandled rejections.
AdapterMongoClientonClose@auth/mongodb-adapter