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
This creates the API endpoint:
http://localhost:3000/api/auth/register
⚙️ 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 },
);
}
}
🧠 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";
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)
This means the API will run when we send a POST request.
Example API URL
/api/auth/register
3️⃣ Read Data from Request
const { email, password } = await request.json();
This reads data sent from the client.
Example request body
{
"email": "user@gmail.com",
"password": "123456"
}
4️⃣ Validate Input Data
if (!email || !password)
If the user does not send email or password the API returns an error.
Example response
{
"error": "Email and password are required"
}
Status code
400 Bad Request
5️⃣ Connect to MongoDB
await connectToDatabase();
This connects the application to the MongoDB database.
The connection uses the MongoDB Atlas connection string stored in:
.env.local
Example
MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/reels-pro
6️⃣ Check if User Already Exists
const existingUser = await User.findOne({ email });
This checks if the email already exists in the database.
Example stored user
{
email: "user@gmail.com",
password: "hashedpassword"
}
If the email already exists the API returns an error.
Example response
{
"error": "Email is already registered"
}
7️⃣ Create New User
If the user does not exist the API creates a new user.
await User.create({
email,
password,
});
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"
}
8️⃣ Send Success Response
return NextResponse.json(
{ message: "User registered successfully" },
{ status: 201 }
);
Status 201 means
Created successfully
🗄 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
This connection string is stored inside
.env.local
📬 Testing the API with Postman
After creating the API we test it using Postman.
Open Postman and create a request.
Request Method
POST
API URL
http://localhost:3000/api/auth/register
Request Body
Select:
Body → raw → JSON
Example request
{
"email": "test@gmail.com",
"password": "123456"
}
Click Send.
✅ Successful Response
If everything works correctly Postman returns
{
"message": "User registered successfully"
}
Status code
201 Created
📊 Check User in MongoDB Atlas
You can verify the saved user in MongoDB Atlas.
Steps
- Open MongoDB Atlas dashboard
- Click your cluster
- Click Browse Collections
- Open your database
- Open the users collection
You will see a document like
{
email: "test@gmail.com",
password: "$2a$10$...",
createdAt: "...",
updatedAt: "..."
}
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)