mirror of
https://github.com/SrIzan10/next-auth.git
synced 2026-05-01 10:55:20 +00:00
* docs: beta initial commit * docs(oauth): finish initial tutorial * docs(oauth-tutorial): finish guide * docs(docusaurus): just log broken links * docs: re-organising beta * docs(beta): sort documents for sorting * docs: more re-structure * docs: more re-structure (2) * fix: more WIP * fix: more WIP * chore: more updates * chore: wip * chore: wip * fix lock file * docs(getting-started): credentials * chore: remove json-server file * chore: cleanup * remove mongodb from dev app * chore: cleanup * revert * chore: cleanup * chore: more cleanup changes Co-authored-by: Balázs Orbán <info@balazsorban.com>
70 lines
1.9 KiB
Markdown
70 lines
1.9 KiB
Markdown
---
|
|
id: mongodb
|
|
title: MongoDB
|
|
---
|
|
|
|
# MongoDB
|
|
|
|
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.
|
|
|
|
## Usage
|
|
|
|
1. Install the necessary packages
|
|
|
|
```bash npm2yarn
|
|
npm install next-auth @next-auth/mongodb-adapter mongodb
|
|
```
|
|
|
|
2. Add `lib/mongodb.js`
|
|
|
|
```js
|
|
// This approach is taken from https://github.com/vercel/next.js/tree/canary/examples/with-mongodb
|
|
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") {
|
|
// 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
|
|
```
|
|
|
|
3. Add this adapter to your `pages/api/[...nextauth].js` next-auth configuration object.
|
|
|
|
```js
|
|
import NextAuth from "next-auth"
|
|
import { MongoDBAdapter } from "@next-auth/mongodb-adapter"
|
|
import clientPromise from "lib/mongodb"
|
|
|
|
// For more information on each option (and a full list of options) go to
|
|
// https://next-auth.js.org/configuration/options
|
|
export default NextAuth({
|
|
adapter: MongoDBAdapter(clientPromise),
|
|
...
|
|
})
|
|
```
|