As a developer, you have various choices when selecting the technology stack for your next application. However, the goal is to choose a technology stack that will meet your needs. Each tool in your technology stack should integrate well with the other tools you use for development and be flexible enough to accommodate changes. Developer productivity is another factor to consider when choosing a development stack for application development.

Next.JS and MongoDB are an excellent combination to help you get your next application up and running. A Next JS MongoDB connection will make it easy to move data from the database and render it on the application. In this article, we will discuss the steps for Next JS MongoDB Connection. A brief introduction to Next JS and MongoDB is also presented. 

What is Next.js?

Next JS mongoDB connection: Next.js logo

Next.js is a popular open-source React framework for building web applications. It is designed to simplify creating robust and efficient React applications by providing a set of conventions and tools. Next.js offers server-side rendering (SSR), automatic code splitting, and an intuitive file-based routing system.

What is MongoDB?

Next JS Mongo DB Connection

MongoDB is a popular open-source, cross-platform, document-oriented NoSQL database management system. It is classified as a NoSQL (non-relational) database because it stores data in flexible, JSON-like documents with dynamic schemas, rather than using tables and rows like in traditional relational databases.

Steps for Next Js MongoDB Connection

We will be building a Next.js app that retrieves data from MongoDB. The app will also allow us to insert data from Next.js into MongoDB. The following steps will guide you through establishing the Next JS MongoDB Connection.

Scale your data integration effortlessly with Hevo’s Fault-Tolerant No Code Data Pipeline

Hevo is the only real-time ELT No-code Data Pipeline platform that cost-effectively automates data pipelines that are flexible to your needs. With integration with 150+ Data Sources (40+ free sources), we help you not only export data from sources & load data to the destinations but also transform & enrich your data, & make it analysis-ready.

Start for free now!

Get Started with Hevo for Free

Step 1: Create a MongoDB Atlas Account

The Next JS MongoDB connection is made easy by MongoDB Atlas. It lets you create and manage MongoDB databases in the cloud through a graphical user interface. 

Next JS MongoDB Connection - Homepage

We need to create a new database within an existing MongoDB cluster. You need to have a MongoDB Atlas account for this. If not, sign up for one here

  • Inside MongoDB, create a new database within a cluster.
  • Inside that database, create a collection.
  • We will give the database the name “nextjs-mongodb-demo” and the collection the name “posts.” 
  • Also, create a collection of “users” and add sample data with details like name, phone number, email, etc. You can then connect to the cluster right from MongoDB Atlas. 

Step 2: Create a Next.JS Project

We now need to create a new Next.js project. Run the following command to create the project:

npx create-next-app nextjs-mongodb-app

The command will create a new Next.js project named
nextjs-mongodb-app

The project can be opened with a code editor such as Visual Studio Code

Before running the subsequent commands, ensure that you have installed Visual Studio Code in your system. 

Run the following commands:

cd nextjs-mongodb-app code

The last command will open the Next.js project in the Visual Studio Code editor. 

Understanding the Project Structure

Upon launching your project in your code editor, many files and folders will be visible. Here’s a quick rundown of the most significant ones:

  • pages: You will generate the pages for your application in this directory. By name, each file is associated with a certain route. For instance, http://localhost:3000/about allows you to visit pages/about.js.
  • public: Static materials, such as pictures, go in this directory. Similar to pages, files that are accessible to the public may be accessed from the application’s root.
  • styles: Your CSS files are located in this directory. Next, you may import CSS and Sass files using the built-in support for JavaScript.files in css and scss.
  • package.json: This file contains the list of project dependencies and scripts. .next: This directory is generated when you build your project and contains the compiled versions of your pages and other assets.
  • node_modules: This directory contains all the packages that your project depends on. It’s created when you run npm install.

Step 3: Set the local environment variable

Image Source

You should copy a connection string from MongoDB Atlas. You can find it under the “Connect Instructions” button of MongoDB Atlas. It should be something like this:

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

In the above connection string, nicky234 is the username, while jc7ap0dFcwvZdo09 is the password

The connection to the database will be made later. 

Step 4: Install MongoDB

We should now install the MongoDB package to use MongoDB in our Next.js app. We will install version 3.5.9 of the package as shown below:

npm i mongodb@3.5.9

Step 5: Next.Js connect to MongoDB Integration

Create a new file inside the lib directory and give it the name mongodb.js. Our goal is to establish our Next js MongoDB connection. Add the following code to the file:

// mongodb.js

import { MongoClient } from 'mongodb'

const uri = process.env.MONGODB_URI
const options = {
  useUnifiedTopology: true,
  useNewUrlParser: true,
}

let client
let clientPromise

if (!process.env.MONGODB_URI) {
  throw new Error('Add Mongo URI to .env.local')
}

if (process.env.NODE_ENV === 'development') {
Replacement).
  if (!global._mongoClientPromise) {
    client = new MongoClient(uri, options)
    global._mongoClientPromise = client.connect()
  }
  clientPromise = global._mongoClientPromise
} else {
  client = new MongoClient(uri, options)
  clientPromise = client.connect()
}

export default clientPromise

Step 6: Access MongoDB

The Next.js framework makes it easy for users to create API endpoints and use them to access databases. 

Create a new file inside the pages/api directory and give it the name posts.js. We will define the POST and GET methods to insert and fetch posts inside the file. This is possible since we have made the Next js MongoDB connection. 

// posts.js

import clientPromise from "../../lib/mongodb";

export default async function handler(req, res) {
  const client = await clientPromise;
  const db = client.db("nextjs-mongodb-demo");
  switch (req.method) {
    case "POST":
      let bodyObject = JSON.parse(req.body);
      let myPost = await db.collection("posts").insertOne(bodyObject);
      res.json(myPost.ops[0]);
      break;
    case "GET":
      const allPosts = await db.collection("allPosts").find({}).toArray();
      res.json({ status: 200, data: allPosts });
      break;
  }
}

Step 7: Fetch the Posts

We can now call the API endpoint and retrieve the posts from the MongoDB database. This means we make a GET request to the API endpoints as shown below:

export async function getServerSideProps(context) {
  let res = await fetch("http://localhost:3000/api/posts", {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
    },
  });
  let allPosts = await res.json();

  return {
    props: { allPosts },
  };
}

Step 8: Create a Post

To create a new post, we only have to call the POST request on the API endpoint as follows:

useEffect(() => {
  setPostsState(allPosts);
}, [allPosts]);

let submitForm = async (e) => {
  setLoading(true);
  e.preventDefault();
  let res = await fetch("http://localhost:3000/api/posts", {
    method: "POST",
    body: JSON.stringify({
      title: title,
      content: content,
    }),
  });
  res = await res.json();
  setPostsState([...postsState, res]);
  setTitle("");
  setContent("");
  setLoading(false);
};

Thus, it is possible to insert data into MongoDB and retrieve it after performing a Next js MongoDB connection. 

Querying MongoDB with Next.js

Now that we have a Next JS MongoDB connection, let’s explore how to fetch and integrate data from our MongoDB database to Next.js.

Example 1: Creating API endpoint with Next.js

Let’s begin by exploring the first approach: creating an API endpoint within our Next.js application to interact with MongoDB. To achieve this, we need to establish a dedicated directory called api inside our pages directory. Every file we create within this api directory will be treated as an individual API endpoint.

Now, let’s proceed to create the api directory and a new file named movies.tsx within it. This endpoint will retrieve and return a list of 20 movies from our MongoDB database. Here’s how we can implement this route:

import clientPromise from "../../lib/mongodb";
import { NextApiRequest, NextApiResponse } from 'next';

export default async (req: NextApiRequest, res: NextApiResponse) => {
    try {
        const client = await clientPromise;
        const db = client.db("sample_mflix");
        const movies = await db
            .collection("movies")
            .find({})
            .sort({ metacritic: -1 })
            .limit(10)
            .toArray();
        res.json(movies);
    } catch (e) {
        console.error(e);
    }
}

Example 2: Integrating MongoDB data into Next.js pages

Now, let’s shift our focus to directly integrating MongoDB data into our Next.js pages. We’ll achieve this by leveraging the getServerSideProps() method provided by Next.js.

The getServerSideProps() method enables server-side rendering for Next.js pages. This means that every time a page is loaded, the getServerSideProps() method runs on the server-side, fetches the necessary data, and passes it to the React component as props. Importantly, the code within getServerSideProps() never reaches the client-side, making it an ideal place to implement our MongoDB queries.

To illustrate this approach, let’s create a new file called movies.tsx within the pages directory. Inside this file, we’ll add the following code:

import clientPromise from "../lib/mongodb";
import { GetServerSideProps } from 'next';


interface Movie {
   _id: string;
   title: string;
   metacritic: number;
   plot: string;
}


interface MoviesProps {
   movies: Movie[];
}


const Movies: React.FC<MoviesProps> = ({ movies }) => {
   return (
       <div>
           <h1>Top 20 Movies of All Time</h1>
           <p>
               <small>(According to Metacritic)</small>
           </p>
           <ul>
               {movies.map((movie) => (
                   <li key={movie._id}>
                       <h2>{movie.title}</h2>
                       <h3>{movie.metacritic}</h3>
                       <p>{movie.plot}</p>
                   </li>
               ))}
           </ul>
       </div>
   );
};


export default Movies;


export const getServerSideProps: GetServerSideProps = async () => {
   try {
       const client = await clientPromise;
       const db = client.db("sample_mflix");
       const movies = await db
           .collection("movies")
           .find({})
           .sort({ metacritic: -1 })
           .limit(20)
           .toArray();
       return {
           props: { movies: JSON.parse(JSON.stringify(movies)) },
       };
   } catch (e) {
       console.error(e);
       return { props: { movies: [] } };
   }
};

What do you achieve by Next JS MongoDB Connection?

  1. MongoDB provides high performance for data reads/writes in Next.js apps compared to traditional SQL databases by leveraging indexes and non-relational design.
  2. MongoDB gives your Next.js app access to a NoSQL database to persistently store and retrieve data like user information, content, etc. This data remains intact even when the app server restarts.
  3. MongoDB’s built-in redundancy and failover capabilities reduce the server footprint for highly available Next.js app deployments.
  4. MongoDB uses MongoDB Atlas to offer cloud-hosted services. Utilizing MongoDB’s cloud-native features, you can execute it anywhere.
  5. It’s simple to implement. Since MongoDB offers cloud-hosted access, it’s simple to deploy your full-stack application to hosting providers like Vercel. These cloud platforms function flawlessly with your MongoDB and Next.js workflow.
  6. Next.js and MongoDB with One Click—With just one click, you can generate a complete boilerplate application for Next.js and MongoDB, which you can then utilize to develop your own comprehensive Next.js and MongoDB apps.
  7. Next.js is a framework that supports static site generation (SSG) and server-side rendering (SSR). This implies that running MongoDB doesn’t require a separate server. You can operate your whole MongoDB and Next.js infrastructure inside of a single code base when you use Next.js.
  8. Next.js offers a list of developer perks, including better community support, quick refreshes, automatic Typescript configuration, API routes for Node.js serverless services, and more.

Common Issues and Their Solutions

Issue 1: Unsupported HTTP Method

Indicates that the HTTP method you are using to request data from your API endpoint is not supported. Verify that every HTTP method you use in your API route is being handled.

Issue 2: Unable to Connect to Database

Verify that your MongoDB connection string is right if you’re having trouble connecting to your database. Additionally, see if your MongoDB Atlas cluster has whitelisted your IP address.

Issue 3: Environment Variables Not Working

Make sure you’ve added your environment variables to your.env.local file and that you’re restarting your development server after making changes to this file if your environment variables aren’t functioning. Make sure you’ve added your deployment 

Issue 4: Data Not Showing Up in MongoDB Atlas

Make sure your CRUD operations are operating successfully and that you are properly connecting to your MongoDB database if your data is not appearing in MongoDB Atlas. Additionally, see whether your server logs include any error warnings.

Best Practices for Using Next js MongoDB Connection

  • When handling sensitive data, use environment variables.
  • End Your Connection to MongoDB
  • Appropriately Address Errors
  • Use the Right HTTP Methods
  • Use Indexes in MongoDB
  • Validate Request Data
  • Keep Your Code DRY

Conclusion

This is what you’ve learned in this article:

  • A combination of Next.js and MongoDB is a promising technology stack to help you create a scalable and high-performance web application. 
  • Next.js is a React-based framework used for developing modern web applications. Its features include automatic code splitting, static exporting, server-side rendering, and others. 
  • MongoDB is a NoSQL database that groups data into documents and collections. 
  • After performing a Next js MongoDB Connection, it is possible to move data between your Next.js app and MongoDB. 

In a nutshell, you have learned about Next Js MongoDB Connection. Next.js is an excellent, fast framework for creating applications. If you are unfamiliar with it, it’s the right time to start learning and exploring it.

Apart from MongoDB, you would use several applications and databases across your business for Marketing, Accounting, Sales, Customer Relationship Management, etc. It is essential to consolidate data from all these sources to get a complete overview of your business performance. To achieve this, you need to assign a portion of your Engineering Bandwidth to Integrate Data from all sources, Clean & Transform it, and finally, Load it to a Cloud Data Warehouse or a destination of your choice for further Business Analytics. All of these challenges can be comfortably solved by a Cloud-Based ETL tool such as Hevo Data.

Visit our Website to Explore Hevo

If you are using MongoDB as your NoSQL Database Management System and searching for a no-fuss alternative to Manual Data Integration, then Hevo can automate this for you. Hevo, with its strong integrations, allows you to not only export & load data but also transform & enrich your data & make it analysis-ready in a jiffy.

Want to take Hevo for a ride? Sign Up for a 14-day free trial and simplify your Data Integration process. Check out the Hevo Pricing details to understand which plan fulfills all your business needs.

Tell us about your experience of learning about the Next Js MongoDB Connection! Share your thoughts with us in the comments section below.

Talha
Software Developer, Hevo Data

Talha is a seasoned Software Developer, currently driving advancements in data integration at Hevo Data, where he have been instrumental in shaping a cutting-edge data integration platform for the past four years. With a significant tenure at Flipkart prior to their current role, he brought innovative solutions to the space of data connectivity and software development.

Sarthak Bhardwaj
Customer Experience Engineer, Hevo

Sarthak brings two years of expertise in JDBC, MongoDB, REST API, and AWS, playing a pivotal role in Hevo's triumph through adept problem-solving and superior issue management.

No-code Data Pipeline for MongoDB