Sebastian Gomez
Build Your REST API with Next.js
Building a REST API with Next.js is very easy. Just follow these steps:
- Create a folder for your route inside the
app/apifolder. - Define your API's HTTP methods as exported functions.
- Use the web standard
Request/Responseto handle communication between client and server.
Below is a detailed example of how to do it.
Valid as of Next.js 16: This post uses the App Router, the default and recommended path since Next.js 13. APIs live in app/api/<route>/route.js via Route Handlers. If you're coming from an older tutorial with pages/api/*, that model (Pages Router) still works but is now considered legacy; below I show the equivalent.
File structure
app
api
hello
route.jsRemember that Next.js API routes are not the same as the Serverless API Functions Vercel offers on its platform, even though they share some similarities.
Endpoint example
In the App Router, each HTTP method is a function exported under its own name (GET, POST, PUT,...). It uses the web standard Request/Response:
// app/api/data/route.js
// Handles the HTTP GET request for the '/api/data' route
export function GET(request) {
// Response.json() creates a JSON response with the right Content-Type and status 200
return Response.json({ estamosEn: "Medellín JS" });
}Notice how much simpler this is than the old pages/api: you no longer touch res.statusCode, res.setHeader, or JSON.stringify by hand, Response.json() takes care of it all.
Multiple methods on the same route
One of the App Router's big advantages: you don't need any routing library (like next-connect). Each method is just another exported function in the same route.js:
// app/api/saludo/route.js
export function GET() {
return new Response("Hola Medellín JS");
}
export function POST() {
return Response.json({ hola: "MedellinJS" });
}
export function PUT() {
return new Response("Hola Amigos");
}If you need CORS, you can add the headers directly to the Response (headers: { "Access-Control-Allow-Origin": "*" }) or handle them in the project's middleware.js, no extra dependencies.
A blog comment CRUD
Routes:
- Create comment:
POST /api/comment - Update comment:
PATCH /api/comment/:id - Delete comment:
DELETE /api/comment/:id - Get one comment:
GET /api/comment/:id - Get all comments:
GET /api/comment
In the App Router, dynamic routes use [id] folders, and each route.js groups that resource's methods:
app
api
comment
route.js // POST /api/comment · GET /api/comment
[id]
route.js // GET/PATCH/DELETE /api/comment/:idThe dynamic parameter arrives in the handler's second argument:
// app/api/comment/[id]/route.js
export async function GET(request, { params }) {
const { id } = await params;
// ...look up the comment by id...
return Response.json({ id });
}
export async function DELETE(request, { params }) {
const { id } = await params;
// ...delete the comment...
return new Response(null, { status: 204 });
}Conclusion
In this post we learned how to:
- Build a REST API with Next.js using the App Router's Route Handlers.
- Define multiple HTTP methods as exported functions, with no need for
next-connect. - Implement a basic CRUD to manage blog comments with dynamic
[id]routes.
Proposed exercises
- Practice by building a REST API to manage users in an application.
- Implement authentication and authorization in your REST API.
- Integrate your REST API with a real database.
Summary
- Building a REST API with Next.js is very easy following the App Router's conventions.
- Route Handlers (
app/api/<route>/route.js) let us handle routes and methods efficiently, using the web standardRequest/Responseand no extra libraries. - You can apply these techniques to implement a blog comment CRUD or any other project you have in mind.
That's all, I hope this post is useful to you and that you can apply it to a project you have in mind. Don't hesitate to leave a comment if it helped, if you have any questions, or if you'd like to add something. Good luck!
Sebastian Gomez
Creador de contenido principalmente acerca de tecnología.