Learning navigation

Code with Animation

Route Handlers (APIs)

Building REST APIs and webhooks using route.ts.

Next.js4 min readConcept 44 of 65

Building APIs

Route Handlers allow you to create custom request handlers for a given route using the standard Web Request and Response APIs.

They are defined in a route.js or route.ts file.

Server-Side Endpoints

While Server Actions are great for mutations, sometimes you need a traditional API endpoint.

Route Handlers are perfect for webhooks (like receiving a Stripe payment success event), external API access, or standard REST endpoints.

HTTP Methods

You create endpoints by exporting functions named after HTTP methods.

Supported methods: GET, POST, PUT, PATCH, DELETE, HEAD, and OPTIONS.

Example: export async function GET(request) { return Response.json({ data: 'hello' }); }

The REST Client

Use the mock REST client below to send different HTTP requests to the /api/users route handler. Watch how the correct exported function is triggered.

HTTP Client

https://api.acme.com/api/users
Response
Awaiting request...

/app/api/users/route.ts

import { NextResponse } from 'next/server';
// Handles HTTP GET requests
export async function GET(request: Request) {
const users = await db.users.findMany();
return NextResponse.json(users);
}
// Handles HTTP POST requests
export async function POST(request: Request) {
const body = await request.json();
const newId = await db.users.create(body);
return NextResponse.json({ success: true, userId: newId }, { status: 201 });
}
// Handles HTTP DELETE requests
export async function DELETE(request: Request) {
await db.users.deleteAll();
return NextResponse.json({ message: 'Deleted' });
}

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What happens if you have both `/app/shop/page.tsx` and `/app/shop/route.ts`?

Remember this

  • Route Handlers are defined in a route.ts file.
  • They export HTTP methods like GET, POST, and DELETE.
  • They use the standard Web Request and Response APIs.
  • You cannot have a route.ts and page.tsx in the exact same folder.

Done with this concept?

Mark it complete to track your progress. No login needed.