DEV Community

Cover image for Register a User and Test API using Postman in Next.js with MongoDB
Himanay Khajuria
Himanay Khajuria

Posted on

Register a User and Test API using Postman in Next.js with MongoDB

When building a full stack application, one common feature is user registration.

This means allowing users to create an account using email and password.

In this blog we will understand how to:

βœ” Create a register API in Next.js

βœ” Connect the API with MongoDB database

βœ” Save a user in the database

βœ” Test the API using Postman

This example uses Next.js App Router, MongoDB and Mongoose.


πŸ“ Project API Structure

In a Next.js App Router project the API route can look like this:

app
 β”” api
   β”” auth
     β”” register
       β”” route.ts
Enter fullscreen mode Exit fullscreen mode

This creates the API endpoint:

http://localhost:3000/api/auth/register
Enter fullscreen mode Exit fullscreen mode

βš™οΈ Register API Code

Below is the API used to register a user.

import { NextRequest, NextResponse } from "next/server";
import { connectToDatabase } from "@/lib/db";
import User from "@/models/User";

export async function POST(request: NextRequest) {
  try {
    const { email, password } = await request.json();

    if (!email || !password) {
      return NextResponse.json(
        { error: "Email and password are required" },
        { status: 400 },
      );
    }

    await connectToDatabase();

    const existingUser = await User.findOne({ email });

    if (existingUser) {
      return NextResponse.json(
        { error: "Email is already registered" },
        { status: 400 },
      );
    }

    await User.create({
      email,
      password,
    });

    return NextResponse.json(
      { message: "User registered successfully" },
      { status: 201 },
    );
  } catch (error) {
    return NextResponse.json(
      { error: "Failed to register User" },
      { status: 500 },
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

🧠 Understanding the Code Step by Step

1️⃣ Import Required Modules

import { NextRequest, NextResponse } from "next/server";
import { connectToDatabase } from "@/lib/db";
import User from "@/models/User";
Enter fullscreen mode Exit fullscreen mode

These imports help us:

β€’ handle HTTP requests

β€’ connect to MongoDB

β€’ access the User model


2️⃣ Create POST API Function

export async function POST(request: NextRequest)
Enter fullscreen mode Exit fullscreen mode

This means the API will run when we send a POST request.

Example API URL

/api/auth/register
Enter fullscreen mode Exit fullscreen mode

3️⃣ Read Data from Request

const { email, password } = await request.json();
Enter fullscreen mode Exit fullscreen mode

This reads data sent from the client.

Example request body

{
 "email": "user@gmail.com",
 "password": "123456"
}
Enter fullscreen mode Exit fullscreen mode

4️⃣ Validate Input Data

if (!email || !password)
Enter fullscreen mode Exit fullscreen mode

If the user does not send email or password the API returns an error.

Example response

{
 "error": "Email and password are required"
}
Enter fullscreen mode Exit fullscreen mode

Status code

400 Bad Request
Enter fullscreen mode Exit fullscreen mode

5️⃣ Connect to MongoDB

await connectToDatabase();
Enter fullscreen mode Exit fullscreen mode

This connects the application to the MongoDB database.

The connection uses the MongoDB Atlas connection string stored in:

.env.local
Enter fullscreen mode Exit fullscreen mode

Example

MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/reels-pro
Enter fullscreen mode Exit fullscreen mode

6️⃣ Check if User Already Exists

const existingUser = await User.findOne({ email });
Enter fullscreen mode Exit fullscreen mode

This checks if the email already exists in the database.

Example stored user

{
 email: "user@gmail.com",
 password: "hashedpassword"
}
Enter fullscreen mode Exit fullscreen mode

If the email already exists the API returns an error.

Example response

{
 "error": "Email is already registered"
}
Enter fullscreen mode Exit fullscreen mode

7️⃣ Create New User

If the user does not exist the API creates a new user.

await User.create({
 email,
 password,
});
Enter fullscreen mode Exit fullscreen mode

The password is stored as a hashed password using bcrypt in the User model.

Example saved user in MongoDB

{
 _id: ObjectId("..."),
 email: "user@gmail.com",
 password: "$2a$10$FJH78S...",
 createdAt: "2025",
 updatedAt: "2025"
}
Enter fullscreen mode Exit fullscreen mode

8️⃣ Send Success Response

return NextResponse.json(
 { message: "User registered successfully" },
 { status: 201 }
);
Enter fullscreen mode Exit fullscreen mode

Status 201 means

Created successfully
Enter fullscreen mode Exit fullscreen mode

πŸ—„ MongoDB Atlas Setup

Before the API works you must connect your project to MongoDB Atlas.

Steps include

βœ” create a cluster

βœ” create a database user

βœ” whitelist your IP address

βœ” copy MongoDB connection string

Example connection string

mongodb+srv://username:password@cluster.mongodb.net/reels-pro
Enter fullscreen mode Exit fullscreen mode

This connection string is stored inside

.env.local
Enter fullscreen mode Exit fullscreen mode

πŸ“¬ Testing the API with Postman

After creating the API we test it using Postman.

Open Postman and create a request.

Request Method

POST
Enter fullscreen mode Exit fullscreen mode

API URL

http://localhost:3000/api/auth/register
Enter fullscreen mode Exit fullscreen mode

Request Body

Select:

Body β†’ raw β†’ JSON
Enter fullscreen mode Exit fullscreen mode

Example request

{
 "email": "test@gmail.com",
 "password": "123456"
}
Enter fullscreen mode Exit fullscreen mode

Click Send.


βœ… Successful Response

If everything works correctly Postman returns

{
 "message": "User registered successfully"
}
Enter fullscreen mode Exit fullscreen mode

Status code

201 Created
Enter fullscreen mode Exit fullscreen mode

πŸ“Š Check User in MongoDB Atlas

You can verify the saved user in MongoDB Atlas.

Steps

  1. Open MongoDB Atlas dashboard
  2. Click your cluster
  3. Click Browse Collections
  4. Open your database
  5. Open the users collection

You will see a document like

{
 email: "test@gmail.com",
 password: "$2a$10$...",
 createdAt: "...",
 updatedAt: "..."
}
Enter fullscreen mode Exit fullscreen mode

This means the API worked correctly.


🎯 Summary

In this project we learned how to:

βœ” Create a register API in Next.js

βœ” Connect the application to MongoDB Atlas

βœ” Save user data in the database

βœ” Test the API using Postman

This is an important step when building authentication systems in full stack applications.


✨ Building APIs and testing them with tools like Postman helps developers understand how the frontend, backend and database work together.

Happy coding πŸ’»πŸš€

Top comments (0)