MongoDB Connect for Next.js or React.js
Before We Begin:
Make sure you’ve installed mongodb and mongoose :
bash
npm install mongodb mongooseThe .env Setup
Add the following environment variables to your .env file:
env
MONGODB_URI=
MONGODB_DBNAME=The Magic Code
Now, pop this into your project to handle MongoDB connection efficiently. Below is an example that uses caching to avoid multiple connections during hot reloads (especially useful in Next.js):
ts
import mongoose, { Mongoose } from "mongoose";
const MONGODB_URL = process.env.MONGODB_URI!;
const MONGODB_DBNAME = process.env.MONGODB_DBNAME!;
interface MongooseConn {
conn: Mongoose | null;
promise: Promise<Mongoose> | null;
}
let cached: MongooseConn = (global as any).mongoose;
if (!cached) {
cached = (global as any).mongoose = {
conn: null,
promise: null,
};
}
export const connect = async () => {
if (cached.conn) return cached.conn;
cached.promise =
cached.promise ||
mongoose.connect(MONGODB_URL, {
dbName: MONGODB_DBNAME,
bufferCommands: false,
connectTimeoutMS: 30000,
});
cached.conn = await cached.promise;
return cached.conn;
};This setup ensures a stable MongoDB connection in both development and production environments. Clean, simple, and efficient.
Tech Stack: Next.js, ShadCN UI, Clerk.js