Connecting MongoDB in Next.js is very easy. Just follow these steps:
1. Install MongoDB Driver
npm install mongodb
(Or yarn add mongodb if you use Yarn.)
2. Create a Database Connection File
Create a file:
/lib/mongodb.js
Add this:
import { MongoClient } from "mongodb";
const uri = process.env.MONGODB_URI;
const options = {};
let client;
let clientPromise;
if (!process.env.MONGODB_URI) {
throw new Error("Please add MONGODB_URI to .env.local");
}
if (process.env.NODE_ENV === "development") {
if (!global._mongoClient) {
global._mongoClient = new MongoClient(uri, options);
}
client = global._mongoClient;
} else {
client = new MongoClient(uri, options);
}
clientPromise = client.connect();
export default clientPromise;
3. Add your MongoDB URL in .env.local
MONGODB_URI=mongodb://localhost:27017/mydatabase
Or for Atlas:
MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/mydb
Restart the server after adding env variables.
4. Use MongoDB in API Routes
Example: app/api/posts/route.js
import clientPromise from "@/lib/mongodb";
export async function GET() {
const client = await clientPromise;
const db = client.db("mydatabase");
const posts = await db.collection("posts").find().toArray();
return Response.json({ posts });
}
5. Insert Data Example
export async function POST(request) {
const body = await request.json();
const client = await clientPromise;
const db = client.db("mydatabase");
await db.collection("posts").insertOne(body);
return Response.json({ message: "Post created!" });
}
✅ Done!
Your Next.js app is now successfully connected to MongoDB.
Top comments (0)