How to Integrate MongoDB in Next.js ?
Last Updated :
23 Jul, 2025
A developer considers various options carefully for his or her tech stack before writing code. The primary objective is choosing a tech stack that aligns with the project requirements. Therefore, each tool within the tech stack must seamlessly integrate with others, creating a collaborative development environment. Equally important is the tech stack's adaptability to changes that may arise during the development process. Apart from technical considerations, the impact on the developer's productivity is also crucial in the decision of the tech stack.

The combination of Next.js and MongoDB is a great choice, as it offers faster development and builds robust software. The combination of Next.js and MongoDB simplifies the process of transferring the data from the database and rendering it within the application, resulting in a smooth workflow. In this article, we are going to explore in a step-by-step manner how to integrate MongoDB and Next.js, creating a basic API to add data and see all data from the database.
What is Next.js?
Next.js is a framework of React that is used for making web applications, increasing the speed of the development process. It simplifies the creation of dynamic and performant websites by providing features such as server-side rendering, automatic code splitting, and an intuitive file-based routing system. As it has built-in support for React Next.js, it enables developers to focus on building UI while taking care of SEO and performance. It is highly extensible, meaning it can integrate with data sources and APIs making it a popular choice in the web development ecosystem.
What is MongoDB?
MongoDB is a NoSQL database system that stores data in flexible JSON-like BSON documents. It is famous for being scalable and flexible. It has a schema-less model, ideal for dynamic and evolving data structures. It is used a lot in modern web development. Distributed architecture allows seamless scalability across servers or clusters. Its simplicity, scalability, and adaptability make it a perfect choice for applications that deal with instructed data.
Integrate MongoDB in Next.js
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 in NextJS
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:
project structureStep 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
We'll be utilizing MongoDB Atlas for our database needs. If you haven't registered with MongoDB yet, please go ahead and sign up. Once you've signed in, proceed to create a cluster. This cluster will serve as a dedicated space to store our database and collections. The advantage is that we can access them remotely without concerns about memory space limitations.
Step 4: Obtaining Connection String and Connecting the Next.js App
Visit the connection settings in your MongoDB cluster and copy the connection string. Think of it as a secure password for accessing your cluster; this ensures that only authorized users can access the cluster. Now to establish a connection between the Next.js application and MongoDB, create a file named .env.local in the root directory of the Next.js project, and inside the file, add the connection string like this:
MONGODB_URI= "mongodb+srv://sam123:<password>@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 <password>.
Step 5: Setting up API Routes for Data Handling
We will be using API routes to communicate with MongoDB. The API routes are going to handle our request data. We will be creating two files in the pages/api folder in our project. If it does not exist, create pages/api folders. Inside of it, create the files with the names saveData.js and getAllData.js. The API getAllData.js is going to get all the records in our database's collection, and saveData.js will save the inputted text into the specific database's specific collection.
JavaScript
// 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!" });
}
}
In the above code, we have defined a Next.js API route, getAllData.js, which is going to respond to GET requests. It connects to the MongoDB database using the provided connection string. Upon a successful connection, it retrieved all documents from a specified collection (user_data_collection) within the database (user_data_db). The fetched data is sent as a JSON response with a status of 200. If there is an error during the process, a status code of 500 is sent. If the HTTP method is not received, then a status code of 405 is sent, stating the method is not allowed. The MongoDB connections are properly handled using asynchronous functions.
JavaScript
//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!" });
}
}
In the above code, we have defined a Next.js API route known as saveData.js that handles POST requests. It connects to MongoDB using the provided connection string. Upon a successful connection, it retrieves data from the request.body and inserts it into a specified collection (user_data_collection) within the database (user_data_db). If the insertion is successful, it responds with a JSON object containing a success message and an HTTP status code of 201. If some error occurs during the process, a status of 500 as a response is sent. The MongoDB connection is properly managed with asynchronous functions, and the server is closed afterward.
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:
- State management:The component uses the useState hook to manage three state variables: inputData for user input, allData to store retrieved data from the database, and showAllData to control the visibility of fetched data.
- Saving Data: The handleSaveData function sends a POST request to the "/api/saveData" endpoint with the input data. Upon a successful response, it triggers an alert indicating successful data saving, and clears the input field.
- Fetching Data: The fetchAllData function sends a GET request to the "/api/getAllData" endpoint. Upon success, it updates the state with the fetched data and sets showAllData to true.
- Rendering:The component renders an input field and two buttons(for saving and fetching of the data) and when Get All Data is button is clicked it renders all the records in an unordered list.
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:
Conclusion
The combination of Next.js and MongoDB stands as a promising tech stack offering scalability, flexibility, and high-performance capabilities for web applications. Next.js is a React-based framework that has features like server-side rendering, etc. MongoDB is a NoSQL database that stores original data in documents and provides flexibility for dynamic applications. The efficient connection between Next.js and MongoDB facilitates the movement of data between applications and databases. This article guided you through the steps to integrate MongoDB and Next.js. Now you have a headstart, delve deeper, and explore to master.
Similar Reads
Next.js Tutorial Next.js is a popular React framework that extends React's capabilities by providing powerful tools for server-side rendering, static site generation, and full-stack development. It is widely used to build SEO-friendly, high-performance web applications easily.Built on React for easy development of f
6 min read
Next js basics
Next.js IntroductionNext.js is a powerful and flexible React framework that has quickly become popular among developers for building server-side rendered and static web applications. Created by Vercel, Next.js simplifies the process of developing modern web applications with its robust feature set. In this article, weâ
5 min read
Getting Started with Next JSNextJS is an open-source React framework for building full-stack web applications ( created and maintained by Vercel ). You can use React Components to build user interfaces, and NextJS for additional features and optimizations. It is built on top of Server Components, which allows you to render ser
9 min read
Next.js InstallationNext.js is a popular React framework that enables server-side rendering and static site generation. It is easy to learn if you have prior knowledge of HTML, CSS, JavaScript, and ReactJS. Installing Next.js involves setting up Node.js and npm, creating a new Next.js project using npx create-next-appa
4 min read
NextJS 14 Folder StructureNext.js, a powerful React framework developed by Vercel, continues to evolve, bringing new features and improvements with each release. Version 14 of Next.js introduces enhancements to the folder structure, making it more efficient for developers to organize their projects. In this article, weâll ex
4 min read
Next.js Create Next AppIn Next.js, the create next app command is used to automatically initialize a new NextJS project with the default configuration, providing a streamlined way to build applications efficiently and quickly.System Requirements:Node.js 12.22.0 or laterNPM 6.14.4 or later OR Yarn 1.22.10 or latermacOS, Wi
3 min read
Deploying your Next.js AppDeploying a Next.js app involves taking your application from your local development environment to a production-ready state where it can be accessed by users over the internet. Next.js is a popular React framework that enables server-side rendering, static site generation, and client-side rendering
3 min read
Next js Routing
Next.js RoutingNext.js is a powerful framework built on top of React that simplifies server-side rendering, static site generation, and routing. In this article, we'll learn about the fundamentals of Next.js routing, explore dynamic and nested routes, and see how to handle custom routes and API routes.Table of Con
6 min read
Next.js Nested RoutesNext.js is a popular React framework that enables server-side rendering and static site generation. One of the key features that enhance the development experience in Next.js is its routing system.While Next.js provides a file-based routing mechanism, implementing nested routes requires some additio
4 min read
Next.js PagesThe Next.js Pages are the components used to define routes in the next application. Next.js uses a file-based routing system that automatically maps files in the pages directory to application routes, supporting static, dynamic, and nested routes for seamless web development. In this article, we wil
3 min read
Next JS Layout ComponentNext JS Layout components are commonly used to structure the overall layout of a website or web application. They provide a convenient way to maintain consistent header, footer, and navigation elements across multiple pages. Let's see how you can create and use a Layout component in Next.js. Prerequ
3 min read
Navigate Between Pages in NextJSNavigating between pages in Next.js is smooth and optimized for performance, with the help of its built-in routing capabilities. The framework utilizes client-side navigation and dynamic routing to ensure fast, smooth transitions and an enhanced user experience.Prerequisites:Node.js and NPMReactJSNe
3 min read
loading.js in Next JSNext JS is a React framework that provides a number of features to help you build fast and scalable web applications. One of these features is loading.js which allows you to create a loading UI for your application.Prerequisites:JavaScript/TypeScriptReactJS BasicsNextJSLoading UI is important becaus
3 min read
Linking between pages in Next.jsIn this article, we are going to see how we can link one page to another in Next.js. Follow the below steps to set up the linking between pages in the Next.js application:To create a new NextJs App run the below command in your terminal:npx create-next-app GFGAfter creating your project folder (i.e.
2 min read
Next.js RedirectsNext.js Redirects means changing the incoming source request to the destination request and redirecting the user to that path only. When the original web application is under maintenance, the users browse or access the web application, and we want to redirect the user to another web page or applicat
4 min read
Next.js Dynamic Route SegmentsDynamic routing is a core feature in modern web frameworks, enabling applications to handle variable paths based on user input or dynamic content. In Next.js 13+, with the introduction of the App Router, dynamic routes are implemented using a folder-based structure inside the app directory.This arti
2 min read
Middlewares in Next.jsMiddlewares in Next.js provide a powerful mechanism to execute custom code before a request is completed. They enable you to perform tasks such as authentication, logging, and request manipulation, enhancing the functionality and security of your application.Table of ContentMiddleware in Next.jsConv
7 min read
Next JS Routing: InternationalizationNext.js allows you to configure routing and rendering for multiple languages, supporting both translated content and internationalized routes. This setup ensures your site adapts to different locales, providing a seamless and localized experience for users across various languages.Prerequisites:NPM
4 min read
Next js Data Fetching
Next js Rendering
How to Reset Next.js Development Cache? Next.js, a widely used React framework, offers server-side rendering, static site generation, and robust development features. However, cached data in your development environment can sometimes cause issues. Resetting the cache ensures you work with the latest data and code. Letâs explore several me
3 min read
Next js Styling
How to Add Stylesheet in Next.js ?In Next.js, adding a stylesheet enhances your app's styling capabilities. Import CSS files directly in your components or pages using ES6 import syntax. Next.js optimizes and includes these styles in the build process, ensuring efficient and modular CSS management.In this post, we are going to learn
4 min read
Controlling the specificity of CSS Modules in a Next.js AppCSS Modules are one of the popular techniques that are used for local scoping CSS in JavaScript behavioral applications. In Next.js applications, CSS Modules are mostly used to generate the unique class names for our styles, preventing them from conflicting with the styles from different components
4 min read
Install & Setup Tailwind CSS with Next.jsTailwind is a popular utility first CSS framework for rapidly building custom User Interfaces. It provides low-level classes, those classes combine to create styles for various components. You can learn more about Tailwind CSS here. Next.js: Next.js is a React-based full-stack framework developed b
2 min read
CSS-in-JS Next JSCSS-in-JS in Next.js enables you to write CSS styles directly within your JavaScript or TypeScript files. This approach allows you to scope styles to components and leverage JavaScript features, improving maintainability and modularity.In this article learn how to use CSS-in-JS in NextJS its syntax,
3 min read
Next.js Styling: SassNext.js supports various styling options, including Sass, which allows for more advanced styling techniques like variables, nested rules, and mixins. Integrating Sass into a Next.js project enhances your styling capabilities and makes managing styles more efficient and maintainable.In this article,
3 min read
Next js Optimizing
Next.js Bundle Optimization to improve PerformanceIn this article, We will learn various ways to improve the performance of the NextJS bundle which results in increasing the performance of NextJS applications in Google PageSpeed Insights or Lighthouse. As per the documentation, NextJS is a React framework that gives you the building blocks to creat
6 min read
Next JS Image Optimization: Best Practices for Faster LoadingLarge and unoptimized images can impact a website's performance on loading time. Optimizing images is necessary to improve the performance of the website. Next.js provides built-in support for image optimization to automate the process, providing a balance between image quality and loading speed. Pr
4 min read
Next.js Functions : generateMetadataNextJS is a React framework that is used to build full-stack web applications. It is used both for front-end as well and back-end. It simplifies React development with powerful features. One of its features is generateMetadata. In this article, we will learn about the generateMetadata function with
3 min read
Lazy Loading in Next.jsLazy loading in NextJS is a technique used to improve the performance and loading times of web applications built with the NextJS framework. With lazy loading, components or modules are loaded only when they are needed, rather than upfront when the page is initially rendered. This means that resourc
4 min read
How to Add Google Analytics to a Next.js Application?Adding Google Analytics to a Next.js application allows you to track and analyze your website's traffic and user actions. This can provide valuable insights into how users interact with your site, helping you make informed decisions to improve user experience and drive business goals. This article h
3 min read
Next.js Static File ServingNext.js allows you to serve static files from the public directory, making them accessible at the root URL. This feature enables easy inclusion of assets like images, fonts, and static HTML files, enhancing your application's functionality and user experience.Static filesAll those files which need t
2 min read
Next js Configuring
Next.js TypeScriptNextJS is a powerful and popular JavaScript framework that is used for building server-rendered React applications. . It provides a development environment with built-in support for TypeScript, as well as a set of features that make it easy to build and deploy web applications. It was developed by Z
4 min read
Next.js ESLintESLint is a widely-used tool for identifying and fixing problems in JavaScript code. In Next.js projects, integrating ESLint helps ensure code quality and consistency by enforcing coding standards and catching errors early in the development process.In this article, we'll explore how to set up ESLin
3 min read
Next.js Environment VariablesEnvironment variables are a fundamental aspect of modern web development, allowing developers to configure applications based on the environment they are running in (development, testing, production, etc.). In Next.js, environment variables provide a flexible and secure way to manage configuration s
3 min read
MDX in Next JSMDXÂ is a lightweight markup language used to format text. It allows you to write using plain text syntax and convert it to structurally valid HTML. It's commonly used for writing content on websites and blogs. In this article we will see more about MDX in Next JSWhat is MDX?MDX stands for Multidimen
4 min read
Next.js src DirectoryThe NextJS src directory is a project structure that is optional but is widely recommended. It helps to organize the project in a well-defined structure.Organizing a Next.js project with a well-planned folder structure is important for readability, scalability, and maintainability. A clear structure
4 min read
Draft Mode Next.jsDraft Mode in Next.js enables content previewing and editing directly within your application, allowing content creators to view changes before publishing. This feature is especially useful for content management systems or any app where content updates need to be reviewed in real-time. We will expl
5 min read
Next.js Security HeadersNext.js security headers help protect your application from common web vulnerabilities by enforcing security policies at the HTTP level. By configuring these headers, you enhance your app's security and ensure safer interactions for your users.In this article, weâll learn about security headers, the
6 min read
Unit Testing in Next JS: Ensuring Code Quality in Your Project Unit testing in Next.js ensures that individual components and functions work as expected. It improves code reliability, helps catch bugs early, and facilitates easier maintenance and refactoring by verifying the correctness of isolated units of code. Unit testing is an essential aspect of software
4 min read