First, you need to install the official MongoDB package:
npm install mongodb
This package allows you to connect to a MongoDB database and perform CRUD operations.
Since Next.js uses both server-side and client-side code, it's good practice to manage your MongoDB connection in a separate file. This ensures the connection is reused and only set up on the server side.
Create a new file at lib/mongodb.js
(or any other preferred folder structure).
// 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 ensure the connection
// is only created once across hot reloads in the Next.js dev server.
if (!global._mongoClientPromise) {
client = new MongoClient(uri, options);
global._mongoClientPromise = client.connect();
}
clientPromise = global._mongoClientPromise;
} else {
// In production, it's fine to create a new connection every time
client = new MongoClient(uri, options);
clientPromise = client.connect();
}
export default clientPromise;
Next.js stores environment variables in the .env.local
file. Create a .env.local
file in the root of your project and add your MongoDB connection string.
MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/mydatabase
Make sure to replace username
, password
, and mydatabase
with your actual MongoDB credentials.
Next.js API routes are perfect for server-side database connections. Create a new API route that uses the MongoDB connection.
For example, create a file pages/api/collection.js
:
// pages/api/collection.js
import clientPromise from '../../lib/mongodb';
export default async function handler(req, res) {
try {
const client = await clientPromise;
const db = client.db("mydatabase");
const collection = await db.collection("mycollection").find({}).toArray();
res.status(200).json(collection);
} catch (error) {
res.status(500).json({ message: "Error connecting to the database", error });
}
}
This route connects to your MongoDB database and fetches all documents from the collection named mycollection
.
You can also fetch MongoDB data using getServerSideProps
to render the data on the server side for a specific page.
Example of a page (pages/index.js
):
// pages/index.js
import clientPromise from '../lib/mongodb';
export async function getServerSideProps() {
const client = await clientPromise;
const db = client.db("mydatabase");
const collection = await db.collection("mycollection").find({}).toArray();
return {
props: {
collection: JSON.parse(JSON.stringify(collection)),
},
};
}
export default function Home({ collection }) {
return (
<div>
<h1>MongoDB Data</h1>
<ul>
{collection.map((item) => (
<li key={item._id}>{item.name}</li>
))}
</ul>
</div>
);
}
You can run your Next.js app locally with:
npm run dev
Access the API route at http://localhost:3000/api/collection
to see the data fetched from MongoDB, or visit the homepage to see server-side-rendered data.
By following these steps, you’ll have your Next.js application successfully connected to MongoDB!