From b0f1fa8b9cdba2f9526535d47e30227bc0e598c7 Mon Sep 17 00:00:00 2001 From: Yasamato Date: Mon, 9 Dec 2024 12:40:41 +0100 Subject: [PATCH] Use example from authjs.dev (#118) --- auth.ts | 4 ++-- lib/db/authDbClient.ts | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 lib/db/authDbClient.ts diff --git a/auth.ts b/auth.ts index 1059f2e3..39661399 100644 --- a/auth.ts +++ b/auth.ts @@ -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], @@ -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', diff --git a/lib/db/authDbClient.ts b/lib/db/authDbClient.ts new file mode 100644 index 00000000..d221c64f --- /dev/null +++ b/lib/db/authDbClient.ts @@ -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