Skip to main content
Version: v4


The MongoDB adapter does not handle connections automatically, so you will have to make sure that you pass the Adapter a MongoClient that is connected already. Below you can see an example how to do this.



When using the NextAuth v4 beta, please make sure to use the next tagged version of your adapter. For more info on adapter changes, see the migration docs

  1. Install the necessary packages
npm install next-auth@beta @next-auth/mongodb-adapter@next mongodb
  1. Add lib/mongodb.js
// This approach is taken from { MongoClient } from "mongodb"
const uri = process.env.MONGODB_URIconst options = {  useUnifiedTopology: true,  useNewUrlParser: true,}
let clientlet clientPromise
if (!process.env.MONGODB_URI) {  throw new Error("Please add your Mongo URI to .env.local")}
if (process.env.NODE_ENV === "development") {  // In development mode, use a global variable so that the value  // is preserved across module reloads caused by HMR (Hot Module Replacement).  if (!global._mongoClientPromise) {    client = new MongoClient(uri, options)    global._mongoClientPromise = client.connect()  }  clientPromise = global._mongoClientPromise} else {  // In production mode, it's best to not use a global variable.  client = new MongoClient(uri, options)  clientPromise = client.connect()}
// Export a module-scoped MongoClient promise. By doing this in a// separate module, the client can be shared across functions.export default clientPromise
  1. Add this adapter to your pages/api/[...nextauth].js next-auth configuration object.
import NextAuth from "next-auth"import { MongoDBAdapter } from "@next-auth/mongodb-adapter"import clientPromise from "lib/mongodb"
export default async function auth(req, res) {  return await NextAuth(req, res, {    adapter: MongoDBAdapter({      db: (await clientPromise).db("your-database")    }),    ...  })}