MongoDB Tutorial
- Home
- Introduction
- Installation
- Connection & Databases
- CRUD Operations
- Comparison Operators
- Logical Operators
- Array Operators
- Evaluation Operators
- Update Operators
- Projection & Sorting
- Cursor Methods
- Querying Nested Docs
- Upserts & Indexes
- Aggregation Framework
- Data Modeling
- Validations & Transactions
- Geospatial Queries
- Advanced Indexing
- MongoDB with Next.js
- Best Practices
MongoDB with Next.js
Integrating MongoDB into a Next.js application is straightforward. The key is to manage your database connection efficiently to avoid excessive connections in serverless environments.
1. Setup Environment Variables
Create a `.env.local` file in your root directory:
MONGODB_URI=mongodb+srv://user:pass@cluster.mongodb.net/my_db?retryWrites=true&w=majority2. Create a Database Utility
It's best to create a shared connection utility to reuse the client across API routes.
// lib/mongodb.js
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 your Mongo URI to .env.local');
}
if (process.env.NODE_ENV === 'development') {
// In development mode, use a global variable to preserve the value
// across module reloads caused by HMR (Hot Module Replacement).
if (!global._mongoClientPromise) {
client = new MongoClient(uri, options);
global._mongoClientPromise = client.connect();
}
clientPromise = global._mongoClientPromise;
} else {
// In production mode, it's best to not use a global variable.
client = new MongoClient(uri, options);
clientPromise = client.connect();
}
export default clientPromise;3. Usage in an API Route
Now you can use the `clientPromise` in your Next.js API routes (e.g., `pages/api/users.js`).
import clientPromise from "../../lib/mongodb";
export default async function handler(req, res) {
const client = await clientPromise;
const db = client.db("my_db");
switch (req.method) {
case "GET":
const users = await db.collection("users").find({}).toArray();
res.json({ status: 200, data: users });
break;
case "POST":
let newUser = await db.collection("users").insertOne(req.body);
res.json({ status: 201, data: newUser });
break;
}
}Recommendation: For more complex data modeling and easier validation, consider using Mongoose instead of the native MongoDB driver.