Topic 28 of 39
Route Handlers
Overview
Route Handlers (route.ts) allow you to create custom API endpoints for external clients, webhooks, or complex REST setups. They replace the pages/api directory from the older Next.js router.
Syntax
typescript
// app/api/users/route.ts
import { NextResponse } from 'next/server';
export async function GET(request: Request) {
const users = [{ id: 1, name: 'Alice' }];
return NextResponse.json(users);
}
export async function POST(request: Request) {
const body = await request.json();
// Save body to DB...
return NextResponse.json({ success: true }, { status: 201 });
}Common Pitfalls
- Naming the file
page.tsinstead ofroute.ts. Route Handlers MUST be namedroute.tsorroute.js. - Putting a
route.tsandpage.tsxin the exact same folder (Next.js will throw a conflict error).
Interview Questions
Q:
When should you use Route Handlers vs Server Actions?
A:
Use Server Actions for mutations/forms strictly within your Next.js frontend. Use Route Handlers when you need to expose a public API, handle webhooks (like Stripe), or serve non-UI content.
Real-World Example
Handling a Stripe webhook asynchronously.
example
typescript
// app/api/webhooks/stripe/route.ts
export async function POST(req: Request) {
const payload = await req.text();
const sig = req.headers.get('stripe-signature');
// Verify Stripe signature...
return new Response('Webhook received', { status: 200 });
}Check Your Knowledge
Test your understanding of Route Handlers with these quick questions.