mongoDB Adapter - NextAuth.js
Open Source. Full Stack. Own Your Data.
Overview
This is the mongoDB Adapter for next-auth
. This package can only be used in conjunction with the primary next-auth
package. It is not a standalone package.
You can find the mongoDB schema in the docs at next-auth.js.org/adapters/mongodb.
Getting Started
- Install
next-auth
and @next-auth/mongodb-adapter
npm install next-auth mongodb @next-auth/mongodb-adapter
- Add
lib/mongodb.js
import { MongoClient } from "mongodb"
const uri = process.env.MONGODB_URI
const options = {
useUnifiedTopology: true,
useNewUrlParser: true,
}
let client
let clientPromise
if (!process.env.MONGODB_URI) {
throw new Error("Please add your Mongo URI to .env.local")
}
if (process.env.NODE_ENV === "development") {
if (!global._mongoClientPromise) {
client = new MongoClient(uri, options)
global._mongoClientPromise = client.connect()
}
clientPromise = global._mongoClientPromise
} else {
client = new MongoClient(uri, options)
clientPromise = client.connect()
}
export default clientPromise
- Add this adapter to your
pages/api/[...nextauth].js
next-auth configuration object.
import NextAuth from "next-auth"
import Providers from "next-auth/providers"
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")
}),
providers: [
Providers.Google({
clientId: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
}),
],
...
})
}
Contributing
We're open to all community contributions! If you'd like to contribute in any way, please read our Contributing Guide.
License
ISC