Next.js with Database

In this tutorial, you will learn, how to use MongoDB with Next.js

I will cover the topics below in this tutorial

  1. How to setup MongoDB
  2. How to connect to MongoDB using Mongoose
  3. How to perform CRUD operations
  4. How to fetch database data in Server Components

1. How to setup MongoDB

You can use local MongoDB or MongoDB Atlas (Cloud)

Now, you will use MongoDB Atlas

There are 3 steps

  1. Go to MongoDB Atlas
  2. Create a free cluster
  3. Copy the connection string

Example: Connection string


mongodb+srv://username:password@cluster.mongodb.net/nextjsdb

2. Install Mongoose Packages

Through the command below, you can install Mongoose.


npm install mongoose

3. Create a Database Connection file

Now, you will create a database connection file (lib/mongodb.js) to connect MongoDB with Next.js.


import mongoose from "mongoose";

const MONGODB_URI = process.env.MONGODB_URI;

if (!MONGODB_URI) {
  throw new Error("Please define MONGODB_URI in .env.local");
}

let cached = global.mongoose;

if (!cached) {
  cached = global.mongoose = { conn: null, promise: null };
}

export async function connectDB() {
  if (cached.conn) return cached.conn;

  if (!cached.promise) {
    cached.promise = mongoose.connect(MONGODB_URI, {
      bufferCommands: false,
    });
  }

  cached.conn = await cached.promise;
  return cached.conn;
}

4. Add Environment Variable

You will create a .env.local file


MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/nextjsdb

5. Create MongoDB Model

You will see, we will create a User model.


import mongoose from "mongoose";

const UserSchema = new mongoose.Schema({
  name: String,
  email: String,
});

export default mongoose.models.User ||
  mongoose.model("User", UserSchema);

6. CRUD Operations in Next.js

We will use Route Handlers for CRUD APIs.

We will create a route.js file in app/api/users/route.js


import { connectDB } from "@/lib/mongodb";
import User from "@/models/User";

// create a POST function
export async function POST(req) {
  await connectDB();
  const body = await req.json();

  const user = await User.create(body);
  return Response.json(user);
}

// create a GET function

export async function GET() {
  await connectDB();
  const users = await User.find();
  return Response.json(users);
}

// Update User (PUT) function
export async function PUT(req) {
  await connectDB();
  const { id, name } = await req.json();

  const user = await User.findByIdAndUpdate(
    id,
    { name },
    { new: true }
  );

  return Response.json(user);
}

// Delete User (DELETE) Function
export async function DELETE(req) {
  await connectDB();
  const { id } = await req.json();

  await User.findByIdAndDelete(id);
  return Response.json({ message: "User deleted" });
}


7. Fetch Data from Database in Server Components

Now, will use App Router as Server Components.

Create a file app/users/page.js and put the code below into it.


import { connectDB } from "@/lib/mongodb";
import User from "@/models/User";

export default async function UsersPage() {
  await connectDB();
  const users = await User.find();

  return (
    <div>
      <h2>User List</h2>
      <ul>
        {users.map((user) => (
          <li key={user._id}>{user.email}</li>
        ))}
      </ul>
    </div>
  );
}

Next.js with Database – Interview Questions

Q 1: How does Next.js connect to databases?
Ans: Using ORMs or database drivers.
Q 2: Common databases used with Next.js?
Ans: PostgreSQL, MySQL, MongoDB.
Q 3: Can databases be accessed in Server Components?
Ans: Yes.
Q 4: What ORMs are popular?
Ans: Prisma, Drizzle.
Q 5: Is Next.js suitable for full-stack apps?
Ans: Yes, it supports frontend and backend in one project.

Next.js with Database – Objective Questions (MCQs)

Q1. Which database is commonly used with Next.js?






Q2. Database connections in Next.js should be made in:






Q3. Which ORM is popular with Next.js?






Q4. Environment variables for database URLs are stored in:






Q5. Why should database logic not be placed in Client Components?






Related Next.js with Database Topics