How to create and connect database in MongoDB Atlas using Next.js — Part-1

Ragu Developer
YavarTechWorks
Published in
4 min readJun 14, 2023

In this article explained what is Next.js and MongoDB and How to connect database.

Next.js :

Next.js is a React framework. It is an open-source framework designed to work with react. Created by Vervcel.

It’s a support for build API endpoints so we can build end-to-end application by Next.js.

Many built-in features available in Next.js

  • Routing : In react, we have use external package for routing but Next.js has support page based routing system. It’s avoid complex configurations and support dynamic routes also
  • Pre-rendering : All applications has rendering process. Pre-render is improve better performance and optimize SEO. It provides three different pre-rendering process. (SSR- Server Side Rendering, SSG-Static Site Generation, ISR-Incremental Site Regeneration)
  • Automatic Code Splitting : Reduce initial load time of a websites and optimize the user experience while browsing. It default to split pages into separate chunks. It can helps for page load faster.
  • API route : Next.js introduced new feature API routes from version 9. It can create serverless functions and handle API requests
  • Built-in CSS : It supports for CSS-in-JS library and SASS
  • Data fetching optimized

Knowledge about : HTML, CSS, Javascript, React

System Requirements:

  • Node.js 16.8 or Later
  • Support to Windows, macOS, Linux OS

Create new project using command : npx create-next-app@latest

Some dependency questions will ask. You can select yes, if need.

Project run command:

npm run dev

MongoDB :

MongoDB is one of the most popular NoSQL database and it’s a open-source document-oriented database and database server. The data stored in the collections and documents. It provides cloud-hosted services.

  • The collections is like a database table
  • The documents is key and value pairs instead of rows and columns .
  • It can store large structured and unstructured data

Features of MongoDB :

  • Schema-less database
  • Document oriented
  • Indexing
  • Replication
  • Scalability
  • Aggregation
  • High performance

MongoDB connection :

I have used MongoDB and MongoDB Atlas for hosting database.

If you don’t have MongoDB Atlas account you can create it and create free shared cluster with provider

Create a free cluster

Once the cluster is created , Next we will connect to the created cluster

And you can select Drivers and get connection string for connect database

The connection string like,

mongodb+srv://raguCT25:<password>@cluster0.icnsm87.mongodb.net/?retryWrites=true&w=majority

and we should replace the <password> to your database password.

And go to the Database Access option in security part and you can add password and give a permission for specified role.

Go to the Network Access option and you can configure 0.0.0.0/0 in IP Access list. It will help for all user’s can access our network.

The all configurations and cluster creations are done. Next we will dive into the Application.

How will connect database through our Next.js Application

Install dependency packages,

npm i mongodb mongoose

Database creation and connection code:( Create db folder inside database.js file)

import mongoose from "mongoose";
// track the connection
let isConnected = false;
export const connectToDataBase = async () => {
mongoose.set("strictQuery", true);
if (isConnected) {
console.log("DB connected already");
return;
}
try {
await mongoose.connect(process.env.MONGODB_URI, {
dbName: "MY_DB",
useNewUrlParser: true,
useUnifiedTopology: true,
});
isConnected = true;
} catch (error) {
console.log(error);
}
};

Configure the next.config.js file,

/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
appDir: true,
serverComponentsExternalPackages: ["mongoose"],
},
webpack(config) {
config.experiments = {
...config.experiments,
topLevelAwait: true,
}
return config
}
}

module.exports = nextConfig

create .env file and save the database connection string

MONGODB_URI="mongodb+srv://USER_ID:PASSWORD@cluster0.icnsm87.mongodb.net/?retryWrites=true&w=majority"

Trigger for database connection,

import { connectToDataBase } from "@db/database";

export const GET = async (request) => {
try {
await connectToDataBase();
//return logic here
} catch (error) {
//return logic here
}
};

Once the Database connection has been completed. You can see the MY_DB database in your MongoDB Atlas.

Next.js is a server-side rendering (SSR) and static site generation (SSG) supported framework. So you don’t need an additional server to run MongoDB.

Using Next.js you can run your whole Next.js and MongoDB infrastructure within a single code base.

If you have any queries or suggestions kindly drop in comment box.

Thank you…

--

--