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)