Skip to content
Migrating from NextAuth.js v4? Read our migration guide.
API reference
@auth/mongodb-adapter

@auth/mongodb-adapter

Official MongoDB adapter for Auth.js / NextAuth.js.

Installation

npm install @auth/mongodb-adapter mongodb

MongoDBAdapterOptions

This is the interface of the MongoDB adapter options.

Properties

collections?

optional collections: {
  Accounts: string;
  Sessions: string;
  Users: string;
  VerificationTokens: string;
};

The name of the MongoDB collections.

Accounts?
optional Accounts: string;
Sessions?
optional Sessions: string;
Users?
optional Users: string;
VerificationTokens?
optional VerificationTokens: string;

databaseName?

optional databaseName: string;

The name you want to give to the MongoDB database

onClose()?

optional onClose: (client) => Promise<void>;

Callback function for managing the closing of the MongoDB client. This could be useful in serverless environments, especially when client is provided as a function returning Promise<MongoClient>, not just a simple promise. It allows for more sophisticated management of database connections, addressing persistence, container reuse, and connection closure issues.

Parameters
ParameterType
clientMongoClient
Returns

Promise<void>


defaultCollections

const defaultCollections: Required<Required<MongoDBAdapterOptions>["collections"]>;

format

const format: {
  from: T;
  to: T & {
     _id: ObjectId;
  };
};

Type declaration

from()

Takes a MongoDB object and returns a plain old JavaScript object

Type parameters
Type parameterValue
TRecord<string, unknown>
Parameters
ParameterType
objectRecord<string, any>
Returns

T

to()

Takes a plain old JavaScript object and turns it into a MongoDB object

Type parameters
Type parameterValue
TRecord<string, unknown>
Parameters
ParameterType
objectRecord<string, any>
Returns

T & { _id: ObjectId; }


MongoDBAdapter()

MongoDBAdapter(client, options): Adapter

Parameters

ParameterTypeDescription
clientPromise<MongoClient> | () => Promise<MongoClient>The MongoDB client. You can either pass a promise that resolves to a MongoClient or a function that returns a promise that resolves to a MongoClient.
Using a function that returns a Promise<MongoClient> could be useful in serverless environments, particularly when combined with options.onClose, to efficiently handle database connections and address challenges with persistence, container reuse, and connection closure.
These functions enable either straightforward open-close database connections or more complex caching and connection reuse strategies.
optionsMongoDBAdapterOptions-

Returns

Adapter

Auth.js © Balázs Orbán and Team - 2024