Next JS MongoDB Connection: 8 Easy Steps

on Express js, MongoDB, React • July 27th, 2022 • Write for Hevo

Next JS MongoDB Connection Featured Image

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 steps for Next js MongoDB Connection. A brief introduction to Next Js and MongoDB is also presented. 

Table of Contents

Prerequisites

This is what you need for this article:

  • Next.js framework
  • React.js library
  • MongoDB
  • MongoDB Atlas

What is Next.JS?

Next.Js Logo
Image Source

Next.js is a React-based framework used for creating modern web applications. Next.js comes with numerous powerful features, including automatic code splitting, server-side rendering, static exporting, and other features that make it easy for developers to build scalable applications that can be used in production environments. 

Next. js has an opinionated nature which means that the framework has a greater focus on developer productivity but has adequate flexibility to offer developers enough choices to handle big architectural decisions. 

What is MongoDB?

MongoDB Logo
Image Source

MongoDB is an open-source, document-oriented database used to store massive data volumes. Instead of organizing data in rows and tables, MongoDB uses documents and collections. The documents are comprised of key-value pairs, which comprise the primary data units in MongoDB. Many documents make a collection equivalent to tables in relational databases. 

Since MongoDB is a NoSQL database, it’s ideal for storing unstructured data, unlike relational databases, which are only suitable for storing structured data. 

Next, we will discuss the necessary steps to perform a Next js MongoDB connection. 

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

As the ability of businesses to collect data explodes, data teams have a crucial role in fueling data-driven decisions. Yet, they struggle to consolidate the scattered data in their warehouse to build a single source of truth. Broken pipelines, data quality issues, bugs and errors, and lack of control and visibility over the data flow make data integration a nightmare.

1000+ data teams rely on Hevo’s Data Pipeline Platform to integrate data from over 150+ sources in a matter of minutes. Billions of data events from sources as varied as SaaS apps, Databases, File Storage, and Streaming sources can be replicated in near real-time with Hevo’s fault-tolerant architecture. What’s more – Hevo puts complete control in the hands of data teams with intuitive dashboards for pipeline monitoring, auto-schema management, and custom ingestion/loading schedules. 

This, combined with transparent pricing and 24×7 support, makes us the most special data pipeline software on review sites.

Take our 14-day free trial to experience a better way to manage data pipelines.

Get started for Free with Hevo!

Steps for Next Js MongoDB Connection

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.

Step 1: Create a MongoDB Atlas Account

MongoDB Atlas makes it easy for you to create and manage MongoDB databases in the cloud through a graphical user interface. 

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. 

Step 3: Set the local environment variable

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 app 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. 

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

Hevo Data, a No-code Data Pipeline, can seamlessly transfer data from a vast sea of 100+ sources such as MongoDB & MongoDB Atlas to a Data Warehouse or a Destination of your choice to be visualized in a BI Tool. It is a reliable, completely automated, and secure service that doesn’t require you to write any code!  

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 integration with 100+ sources & BI tools(Including 40+ Free Sources), 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 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.

No-code Data Pipeline for MongoDB