Skip to content

Commit

Permalink
Use example from authjs.dev (#118)
Browse files Browse the repository at this point in the history
  • Loading branch information
Yasamato authored Dec 9, 2024
1 parent c14587d commit b0f1fa8
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
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

0 comments on commit b0f1fa8

Please sign in to comment.