Integrate MongoDB in Next.js (original) (raw)

Last Updated : 11 Mar, 2026

Choosing the right tech stack ensures seamless integration, adaptability, and developer productivity. Next.js with MongoDB is an ideal combo for fast, efficient development and smooth data handling. This article shows how to connect MongoDB with Next.js to build a simple API for adding and fetching data.

Integrate MongoDB

Now we have a basic understanding of what Next.js and MongoDB are and why it is a great choice to use them together. Let us explore in a step-by-step manner how to integrate MongoDB into Next.js. We will be building a simple UI with two buttons that will make an API call for adding data to the MongoDB collection and another API call for getting all data from the same collection.

Steps to Integrate MongoDB

Learn how to seamlessly connect MongoDB with your Next.js application for efficient data storage and retrieval.

**Step 1: Setting Up Your Next.js Environment

Make sure you have Node.js and npm (Node Package Manager) installed on your computer. Run the following commands to create a Next.js project, and then move into the directory using the second command.

npx create-next-app user_next_app
cd user_next_app

The above set of commands initialize a new Next.js project and changes the current working directory to the newly created project directory named user_website here.

Project Structure:

mongo-next-integration

project structure

**Step 2: Installing Required Dependencies

We need to install some packages to connect our Next.js app to our MongoDB database. Run the following command to install the required dependency.

npm install mongodb

The above command tells npm to install the MongoDB package, which is the official MongoDB driver for Node.js. After running this command, MongoDB Package will be installed, which will allow it to interact with MongoDB databases from within the Next.js application. This will provide us with tools to connect, query, and interact with the MongoDB databases.

The updated dependencies in package.json file are:

"dependencies": {
"mongodb": "^6.8.0",
"next": "14.2.4",
"react": "^18",
"react-dom": "^18"
}

**Step 3: MongoDB Setup and Cluster Initialization

**Step 4: Obtaining Connection String and Connecting the Next.js App

add the connection string like this:

MONGODB_URI= "mongodb+srv://sam123:@cluster0.7cpxz.mongodb.net?retryWrites=true&w=majority"

Here, sam123 is the username; in your case, it will be your username for the MongoDB account. Place your MongoDB password in place of .

**Step 5: Setting up API Routes for Data Handling

// pages/api/getAllData.js

import { MongoClient } from "mongodb";

export default async function handler(req, res) { if (req.method === "GET") { const client = new MongoClient(process.env.MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true, });

    try {
        await client.connect();

        // Choose a name for your database
        const database = client.db("user_data_db");

        // Choose a name for your collection
        const collection = database.collection("user_data_collection");
        const allData = await collection.find({}).toArray();

        res.status(200).json(allData);
    } catch (error) {
        res.status(500).json({ message: "Something went wrong!" });
    } finally {
        await client.close();
    }
} else {
    res.status(405).json({ message: "Method not allowed!" });
}

}

`

//pages/api/saveData.js

import { MongoClient } from "mongodb";

export default async function handler(req, res) { if (req.method === "POST") { const { data } = req.body;

    const client = new MongoClient(process.env.MONGODB_URI, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
    });

    try {
        await client.connect();

        // Choose a name for your database
        const database = client.db("user_data_db");

        // Choose a name for your collection
        const collection = database.collection("user_data_collection");

        await collection.insertOne({ data });

        res.status(201).json({ message: "Data saved successfully!" });
    } catch (error) {
        res.status(500).json({ message: "Something went wrong!" });
    } finally {
        await client.close();
    }
} else {
    res.status(405).json({ message: "Method not allowed!" });
}

}

`

**Step 6: Code to Save and Get Data from MongoDB

Create a file named index.js in the pages folder. This will have the UI code showing two buttons to save user inputted data into the database's collection and getAllData from the user_data_collection in the user_data_db.

JavaScript `

// pages/index.js import { useState, useEffect } from "react";

export default function Home() { const [inputData, setInputData] = useState(""); const [allData, setAllData] = useState([]);

// New state variable
const [showAllData, setShowAllData] = useState(false); 

const handleSaveData = async () => {
    const response = await fetch("/api/saveData", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({ data: inputData }),
    });

    if (response.ok) {
        alert("Data saved successfully!");
        setInputData("");
    } else {
        alert("Something went wrong!");
    }
};

const fetchAllData = async () => {
    const response = await fetch("/api/getAllData");

    if (response.ok) {
        const data = await response.json();
        setAllData(data);
        setShowAllData(true);
    } else {
        alert("Failed to fetch data!");
    }
};

return (
    <div>
        <input type="text" value={inputData} onChange={(e) => setInputData(e.target.value)} />
        <button onClick={handleSaveData}>Save Data</button>
        
        {/* Call fetchAllData on button click */}
        <button onClick={fetchAllData}>Get All Data</button> 
        
        {/* Conditionally render the div based on the state */}
        {showAllData && (
            <div>
                <h2>All Data</h2>
                <ul>
                    {allData.map((item) => (
                        <li key={item._id}>{item.data}</li>
                    ))}
                </ul>
            </div>
        )}
    </div>
);

}

`

The provided code is a React component (index.js) in a Next.js project, implementing functionality to interact with a MongoDB database. Key points:

Overall, this code integrates a user interface with the Next.js API routes to save and retrieve data from a MongoDB database.

**Step 7: Start Your Next.js App

Finally, start your Next.js app using the following command:

npm run dev

Visit **http://localhost:3000 in your browser to see your Next.js app in action, now integrated with MongoDB.

**Must Read: