diff --git a/src/utils/auth/adapterFunctions.ts b/src/utils/auth/adapterFunctions.ts index e8b38a5..88b624e 100644 --- a/src/utils/auth/adapterFunctions.ts +++ b/src/utils/auth/adapterFunctions.ts @@ -1,7 +1,15 @@ import { MongoDBAdapter } from "@auth/mongodb-adapter"; -import mongoClient from "../mongodb.config"; +import getClientPromise from "../mongodb.config"; import { Adapter } from "next-auth/adapters"; -const adapter = MongoDBAdapter(mongoClient) as Adapter; +let adapter: Adapter; + +try { + const client = getClientPromise(); + adapter = MongoDBAdapter(client) as Adapter; +} catch (error) { + console.error("Failed to create MongoDB adapter:", error); + // Provide a fallback or throw an error based on your requirements +} export { adapter }; diff --git a/src/utils/mongodb.config.ts b/src/utils/mongodb.config.ts index 30f0ae1..32138a0 100644 --- a/src/utils/mongodb.config.ts +++ b/src/utils/mongodb.config.ts @@ -1,33 +1,33 @@ -// This approach is taken from https://github.com/vercel/next.js/tree/canary/examples/with-mongodb import { MongoClient } from "mongodb"; -if (!process.env.MONGO_URL) { - throw new Error('Invalid/Missing environment variable: "MONGO_URL"'); +if (!process.env.MONGODB_URI) { + throw new Error('Invalid/Missing environment variable: "MONGODB_URI"'); } -const uri = process.env.MONGO_URL; +const uri = process.env.MONGODB_URI; const options = {}; let client; -let mongoClient: Promise; +let clientPromise; -if (process.env.NODE_ENV === "development") { - // In development mode, use a global variable so that the value +function getClientPromise() { let globalWithMongo = global as typeof globalThis & { _mongoClientPromise?: Promise; }; - // is preserved across module reloads caused by HMR (Hot Module Replacement). - if (!globalWithMongo._mongoClientPromise) { + 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 (!globalWithMongo._mongoClientPromise) { + client = new MongoClient(uri, options); + globalWithMongo._mongoClientPromise = client.connect(); + } + clientPromise = globalWithMongo._mongoClientPromise; + } else { client = new MongoClient(uri, options); - globalWithMongo._mongoClientPromise = client.connect(); + clientPromise = client.connect(); } - mongoClient = globalWithMongo._mongoClientPromise; -} else { - // In production mode, it's best to not use a global variable. - client = new MongoClient(uri, options); - mongoClient = client.connect(); + + return clientPromise; } -// Export a module-scoped MongoClient promise. By doing this in a -// separate module, the client can be shared across functions. -export default mongoClient; +export default getClientPromise;