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
bashyarn add mongoose
or
bashnpm 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
jsonMONGODB_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
jsximport 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.

2.1 Create a new project
Click on the New project button

Enter your app name, then click next button

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.

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

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.

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.

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

Choose Drivers options

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

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

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:

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)

Click Add Current IP Address button

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:
jsimport { 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)

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

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
jsimport 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
jsexport 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
jsimport { 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

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

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