Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use example from authjs.dev #118

Merged
merged 1 commit into from
Dec 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { MongoDBAdapter } from '@auth/mongodb-adapter'
import type { NextAuthConfig } from 'next-auth'
import { findOneTyped } from './lib/db/dbTyped'
import { Types } from './types/Components'
import clientPromise from './lib/db/mongoDB'
import client from './lib/db/authDbClient'

export const authOptions: NextAuthConfig = {
providers: [Discord],
Expand Down Expand Up @@ -85,7 +85,7 @@ export const authOptions: NextAuthConfig = {
},

// A database is optional, but required to persist accounts in a database
adapter: MongoDBAdapter(clientPromise, {
adapter: MongoDBAdapter(client, {
collections: {
Users: 'nextauth_users',
Sessions: 'nextauth_sessions',
Expand Down
37 changes: 37 additions & 0 deletions lib/db/authDbClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// This approach is taken from https://github.com/vercel/next.js/tree/canary/examples/with-mongodb
import { MongoClient, ServerApiVersion } from 'mongodb'

if (!process.env.DATABASE_URL) {
throw new Error('Invalid/Missing environment variable: "DATABASE_URL"')
}

const uri = process.env.DATABASE_URL
const options = {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
},
}

let client: MongoClient

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).
let globalWithMongo = global as typeof globalThis & {
_mongoClient?: MongoClient
}

if (!globalWithMongo._mongoClient) {
globalWithMongo._mongoClient = new MongoClient(uri, options)
}
client = globalWithMongo._mongoClient
} else {
// In production mode, it's best to not use a global variable.
client = new MongoClient(uri, options)
}

// Export a module-scoped MongoClient. By doing this in a
// separate module, the client can be shared across functions.
export default client
Loading