How to create API endpoints in Next.js?

In this tutorial, you will learn how to create API endpoints in Next.js.

Next.js allows you to create API endpoints easily using Route Handlers. Each file inside /app/api/ becomes an API endpoint.

Create the API endpoints.

Step 1: Create a Folder

Suppose you will create a users folder for endpoints.


app/
└── api/
    └── users/
         ├── route.js // GET, POST
         └── [id]/
              └── route.js // PUT, DELETE

Step 2: Create a GET Request

Access URL: GET /api/users

Example:


import { NextResponse } from 'next/server';

export async function GET() {
const users = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Tom' }
];

return NextResponse.json(users);
}

Step 3: POST Request in Next.js

Now, you will create a new user through this.

Access URL: POST /api/users

Example:


import { NextResponse } from 'next/server';

export async function POST(request) {
const body = await request.json();

const newUser = {
id: 3,
name: 'Mark'
};

return NextResponse.json(
{ message: 'User created', user: newUser },
{ status: 201 }
);
}

Step 4: PUT Request in Next.js

PUT request is used to update existing records.

Access URL: PUT /api/users/1

Folder structure:


app/api/users/[id]/route.js

Example:


import { NextResponse } from 'next/server';

export async function PUT(request, { params }) {
const { id } = params;
const body = await request.json();

return NextResponse.json({
message: `User ${id} updated`,
updatedData: body
});
}

Step 5: DELETE Request in Next.js

The delete request is used to delete the records.

Folder structure:


app/api/users/[id]/route.js

Example:


import { NextResponse } from 'next/server';

export async function DELETE(request, { params }) {
const { id } = params;

return NextResponse.json({
message: `User ${id} deleted`
});
}

How to create API endpoints in Next.js? – Interview Questions

Q 1: How do you create an API endpoint?
Ans: By creating a route.js file in app/api/.
Q 2: What does route.js export?
Ans: HTTP method functions like GET() or POST().
Q 3: Can middleware be used with API routes?
Ans: Yes.
Q 4: Are API routes scalable?
Ans: Yes, especially when deployed on Vercel.
Q 5: Can authentication be added?
Ans: Yes, using tokens or NextAuth.js.

How to create API endpoints in Next.js? – Objective Questions (MCQs)

Q1. Which HTTP method is used to fetch data from an API?






Q2. Which function handles GET requests in route.js?






Q3. Which object is used to send a response in API routes?






Q4. Which HTTP method is used to send data to the server?






Q5. Which format is commonly returned from API routes?






Related How to create API endpoints in Next.js? Topics