Recent Post:
Categories:
Connecting to a MongoDB database in a Next.js application is straightforward. Here’s a step-by-step guide to setting it up:
First, install the MongoDB package via npm or yarn.
code
//bash
npm install mongodb or yarn add mongodb"
Create a utility file to manage the database connection.
code
// lib/mongodb.js
import { MongoClient } from 'mongodb';
const uri = process.env.MONGO_URL;
let client;
let clientPromise;
if (!uri) {
throw new Error('Please add your Mongo URI to .env.local');
}
if (process.env.NODE_ENV === 'development') {
if (!global._mongoClientPromise) {
client = new MongoClient(uri);
global._mongoClientPromise = client.connect();
}
clientPromise = global._mongoClientPromise;
} else {
client = new MongoClient(uri);
clientPromise = client.connect();
}
export default clientPromise;
Use this connection in your API routes or pages.
code
// pages/api/posts.js
import clientPromise from '../../lib/mongodb';
export default async function handler(req, res) {
const client = await clientPromise;
const db = client.db('mydatabase');
const posts = await db.collection('posts').find().toArray();
res.status(200).json(posts);
}
By following these steps, you can efficiently establish a connection with MongoDB in your Next.js application, enabling you to perform database operations seamlessly.