0
0
NextjsHow-ToBeginner · 4 min read

How to Use MongoDB with Next.js: Simple Guide

To use MongoDB with Next.js, create API routes in the pages/api folder that connect to MongoDB using the official mongodb Node.js driver. Use these API routes to perform database operations securely on the server side, then fetch data from your React components.
📐

Syntax

In Next.js, you use API routes to interact with MongoDB. The main parts are:

  • Import MongoClient: From the mongodb package to connect to the database.
  • Connect to MongoDB: Use a connection string to create a client.
  • Define API handler: Export a default async function that handles requests.
  • Perform database operations: Use the client to query or update collections.
javascript
import { MongoClient } from 'mongodb';

const uri = process.env.MONGODB_URI;
const client = new MongoClient(uri);

export default async function handler(req, res) {
  await client.connect();
  const db = client.db('your-db-name');
  const collection = db.collection('your-collection');

  if (req.method === 'GET') {
    const data = await collection.find({}).toArray();
    res.status(200).json(data);
  } else {
    res.status(405).end(); // Method Not Allowed
  }
}
💻

Example

This example shows a Next.js API route that connects to MongoDB, fetches all documents from a collection, and returns them as JSON. It demonstrates how to securely use MongoDB on the server side and fetch data from a React component.

javascript
import { MongoClient } from 'mongodb';

const uri = process.env.MONGODB_URI;
const client = new MongoClient(uri);

export default async function handler(req, res) {
  try {
    if (!client.topology || !client.topology.isConnected()) await client.connect();
    const db = client.db('testdb');
    const collection = db.collection('items');

    if (req.method === 'GET') {
      const items = await collection.find({}).toArray();
      res.status(200).json(items);
    } else if (req.method === 'POST') {
      const newItem = req.body;
      const result = await collection.insertOne(newItem);
      res.status(201).json({ insertedId: result.insertedId });
    } else {
      res.status(405).json({ message: 'Method not allowed' });
    }
  } catch (error) {
    res.status(500).json({ error: 'Database error' });
  }
}
Output
GET request returns JSON array of documents from 'items' collection; POST request inserts a document and returns insertedId.
⚠️

Common Pitfalls

Common mistakes when using MongoDB with Next.js include:

  • Not reusing the MongoDB client connection, causing performance issues.
  • Exposing database credentials in the client-side code instead of environment variables.
  • Not handling different HTTP methods properly in API routes.
  • Forgetting to parse JSON body in POST requests.

Always keep your connection logic outside the handler to reuse connections and use environment variables for sensitive data.

javascript
/* Wrong: Creating new client on every request */
export default async function handler(req, res) {
  const client = new MongoClient(process.env.MONGODB_URI);
  await client.connect();
  // ...
}

/* Right: Reuse client connection */
import { MongoClient } from 'mongodb';

const client = new MongoClient(process.env.MONGODB_URI);

export default async function handler(req, res) {
  if (!client.topology || !client.topology.isConnected()) await client.connect();
  // ...
}
📊

Quick Reference

Tips for using MongoDB with Next.js:

  • Use pages/api for server-side database logic.
  • Store your MongoDB URI in .env.local as MONGODB_URI.
  • Reuse MongoClient to avoid connection overhead.
  • Handle HTTP methods explicitly in API routes.
  • Fetch data from API routes in React components using fetch.

Key Takeaways

Use Next.js API routes to securely connect and interact with MongoDB on the server side.
Reuse the MongoClient instance to improve performance and avoid multiple connections.
Keep your MongoDB connection string in environment variables, never expose it to the client.
Handle HTTP methods explicitly in your API routes to support different operations.
Fetch data from your API routes in React components to keep database logic separate.