Skip to content
Open
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
12 changes: 10 additions & 2 deletions src/utils/auth/adapterFunctions.ts
Original file line number Diff line number Diff line change
@@ -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 };
36 changes: 18 additions & 18 deletions src/utils/mongodb.config.ts
Original file line number Diff line number Diff line change
@@ -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<MongoClient>;
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<MongoClient>;
};
// 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;