DEV Community

Cover image for Connect MongoDB to Next.JS Like a Pro
Shashwat Pritish
Shashwat Pritish

Posted on

Connect MongoDB to Next.JS Like a Pro

Connecting MongoDB in Next.js is very easy. Just follow these steps:


1. Install MongoDB Driver

npm install mongodb
Enter fullscreen mode Exit fullscreen mode

(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;
Enter fullscreen mode Exit fullscreen mode

3. Add your MongoDB URL in .env.local

MONGODB_URI=mongodb://localhost:27017/mydatabase
Enter fullscreen mode Exit fullscreen mode

Or for Atlas:

MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/mydb
Enter fullscreen mode Exit fullscreen mode

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 });
}
Enter fullscreen mode Exit fullscreen mode

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!" });
}
Enter fullscreen mode Exit fullscreen mode

✅ Done!

Your Next.js app is now successfully connected to MongoDB.

Top comments (0)