logo image
  • Build progress docs

    • Start NextJs project
    • Install linting and formatting (optional)

    • Setup Mongo DB
    • Setup authentication

    • Setup dark mode
    • Multiple languages
    • Setup online payment

    • Setup live chat
    • Setup Top Progress Loader
  • Other tech docs

    • Useful commands in Yarn
    • Basic Git tutorial
    • Basic Gitlab
    • Install WSL in Window
    • Testing - Jest testing library
    • Tools

    • Using icons in NextJs
    • Setup environment variables
    • Basic of Moongoose, MongDB
    • Unitest in Next.js
    • NVM - Node version management
    • Write CI/CD Gitlab for Next.js
    • Setup Messenger live chat for Next.js/React.js
  1. Home
  2. Build Progress Docs
  3. Setup Mongodb

Setup MongoDB for Next.js

Learn how to set up MongoDB in Next.js using Mongoose and MongoDB Atlas. This step-by-step guide covers database connection, schema modeling, and best practices for seamless integration in your Next.js app.


1. Setup codes

1.1 Add Moogose lib for Next.js

We will use moogose lib for handle connect and use the MongoDB

bash
yarn add mongoose

or

bash
npm install mongoose

1.2 Add environment variables config

Add appConfig file on the root of folder (you can handle the env base on your way)

jsx
/* eslint-disable import/no-anonymous-default-export */ export default { // Mongo DB MONGODB_DB: { NAME: process.env.MONGODB_DB_NAME, USERNAME: process.env.MONGODB_DB_USERNAME, PASSWORD: process.env.MONGODB_DB_PASSWORD, CLUSTER_URL: process.env.MONGODB_DB_CLUSTER_URL, }, }

on the .evn (or .env.local) file you need to add 4 values

json
MONGODB_DB_NAME="xxxxxxxxxxxxxxx" MONGODB_DB_USERNAME="xxxxxxxxxxxxxxx" MONGODB_DB_PASSWORD="xxxxxxxxxxxxxxx" MONGODB_DB_CLUSTER_URL="xxxxxxxxxxxxxxx"

Note: All these values will be added in next step

1.3 Add function to connect to MongoDB on MongoDB Atlas

Add file libs/db/mongodb.ts then add this code bellow

jsx
import mongoose from "mongoose"; import config from "@/config"; const MONGODB_URI = `mongodb+srv://${config.MONGODB_DB.USERNAME}:${config.MONGODB_DB.PASSWORD}@${config.MONGODB_DB.CLUSTER_URL}/${config.MONGODB_DB.NAME}?retryWrites=true&w=majority`; if (!MONGODB_URI) { throw new Error("Please define the MONGODB_URI environment variable inside .env.local"); } let cached = global.mongoose; if (!cached) { cached = global.mongoose = { conn: null, promise: null }; } async function dbConnect() { if (cached.conn) { return cached.conn; } if (!cached.promise) { const opts = { bufferCommands: false, }; cached.promise = mongoose.connect(MONGODB_URI, opts).then((mongoose) => { console.info("Db connected"); return mongoose; }); } try { cached.conn = await cached.promise; } catch (e) { cached.promise = null; throw e; } return cached.conn; } export default dbConnect;

2. Signin and setup MongoDB Atlas

MongoDB Atlas is a cloud-based database service provided by MongoDB. It allows developers to deploy, manage, and scale MongoDB databases easily without worrying about infrastructure

Signin or signup on this link. After signin we will see the your organization (you can create new organization), in organization we have multiple projects. Each projects represent your applications. If yoo build a new application, you need create a new project.

mongodb atlas overview

2.1 Create a new project

Click on the New project button

mongodb atlas

Enter your app name, then click next button

mongodb atlas

You can add other people into your project who can contribute use your database, if you don't have other members, you don't care about this. By default, your account will be Project owner, you can have all permission for your project.

mongodb atlas

2.2 Create a new cluster

After create a new project, you need to create a new cluster in your project:

mongodb atlas

If you just for dev and learn about the MongoDB and MongoDB Atlas, you can choose the Free Cluster. You can choose the region where nearest your location.

mongodb atlas

Please copy the username and password, then update the .env file on step 1.2 (MONGODB_DB_USERNAME, MONGODB_DB_PASSWORD). After that, you click "Create Database User" to create user who can access (get, add, update and delete) data.

mongodb atlas

After that, we will choose the way to connect to your Next.js application

mongodb atlas

Choose Drivers options

mongodb atlas

Because we are using Next.js so we need choose the drivers is Node.js

mongodb atlas

Copy the text from @ to / paste into the .env file MONGODB_DB_CLUSTER_URL (in step 1.2)

mongodb atlas

After this step, we had three values: MONGODB_DB_USERNAME, MONGODB_DB_PASSWORD, MONGODB_DB_CLUSTER_URL. The last value we need is MONGODB_DB_NAME. You can name your DB with random value like: app-name-db-dev, app-name-db-pro, ...

Finally, we have the .env file like this:

mongodb atlas

2.3 Add your current IP address

To connect to your MongoDB Atlas server, you need add your current IP address into the whitelist IP address. It is just for security (do not allow someone can connect into your DB).

Click "Network access" link on the left navigation (still in Project page)

mongodb atlas

Click Add Current IP Address button

mongodb atlas

3. Test connection

Now, we have both code to connection and all config values to MongoDB Atlas, now we will test our connection.

You can add the connection function in any route.ts file (route handler in Next.js).In my case, I add into the /api/route.ts file to test it:

js
import { NextResponse } from "next/server"; import dbConnect from "@/libs/db/mongodb"; export async function GET() { const client = await dbConnect(); return NextResponse.json({ message: "Hello World" }); }

Call this API by Chrome (you can use the Postman)

mongodb atlas

View the termial, you can see the log "DB connected".

mongodb atlas

So we can connect into the DB on the MongoDB Atlas.

4. Test add some data into DB

Add User model, create file libs/db/models/User.ts, then add this code below

js
import mongoose, { Model, Schema } from "mongoose"; import { IUser } from "@/types/user"; export interface IUserDocument extends IUser, Document {} const UserSchema: Schema = new Schema<IUserDocument>({ firstName: { type: String, required: true }, lastName: { type: String, required: true }, email: { type: String, required: true, unique: true }, password: { type: String, required: true }, signUpBy: { type: String, required: true }, image: { type: String, required: false }, verification: { type: { code: { type: String }, expires: { type: Date }, }, required: false, }, }); const User: Model<IUserDocument> = mongoose.models.User || mongoose.model<IUserDocument>("User", UserSchema); export default User;

Add User interface in this file types/user.d.ts

js
export interface IUser extends Document { firstName: string; lastName: string; email: string; password: string; signUpBy: "credentials" | "google" | "facebook" | "github"; image?: string; verification?: { code: string; expires: Date; }; }

Update again /api/route.ts file

js
import { NextResponse } from "next/server"; import User from "@/libs/db/models/User"; import dbConnect from "@/libs/db/mongodb"; export async function GET() { await dbConnect(); await User.create({ firstName: "Tu", lastName: "Anh", email: "testabc123@gmail.com", password: "Abc123!@#", signUpBy: "google", }); return NextResponse.json({ message: "User created successfully!" }); }

Call the API again

mongodb atlas

Now open the MongoDB Atlas, go into cluster, then browser the collections (collections basically like table in SQL)

mongodb atlas

Now, you can see, the user data was added into the DB

mongodb atlas
Previous
Install linting and formatting (optional)
Next
Setup authentication

On this page

  1. 1. Setup codes

    1. 1.1 Add Moogose lib for Next.js
    2. 1.2 Add environment variables config
    3. 1.3 Add function to connect to MongoDB on MongoDB Atlas
  2. 2. Signin and setup MongoDB Atlas

    1. 2.1 Create a new project
    2. 2.2 Create a new cluster
    3. 2.3 Add your current IP address
  3. 3. Test connection

  4. 4. Test add some data into DB