Route Handlers — HTTP Endpoints via app/api/.../route.ts
Route Handlers — HTTP Endpoints via app/api/.../route.ts
💡 Why Learn This? — When Server Actions Alone Are Not Enough
Named Exports · Request/Response · Dynamic Segments
1. File Path = URL
2. Named Exports per HTTP Method
No more branching with if (req.method === 'POST') per method.
3. Dynamic Segments → params Argument
4. NextRequest / NextResponse — Richer Functionality
5. Caching Behavior — Dynamic by Default
6. Division of Responsibility with Server Actions
💡 💡 Route Handlers in Practice — Top 5 Tips
1. Named exports per method — no need for switch statements
Calling an undeclared method automatically returns 405.
2. Dynamic segments go in the second argument: params
The first argument is the request; the second is context (which contains params). Don't confuse them.
3. NextResponse.json() vs Response.json() — nearly the same, but
- ▸
Response.json(): Web standard, Edge-compatible. - ▸
NextResponse.json(): Extends the standard with conveniences like cookies and redirect.
Use NextResponse when you need to set cookies or redirect; either works for simple JSON responses.
4. Check whether a Server Action is sufficient first
If a mutation is only called from React components, a Server Action is cleaner than a Route Handler. Use Route Handlers only when external callers are involved.
5. Caching policy — only GET is cached; mutating methods are always dynamic
Use force-dynamic if the database changes frequently; leave the default if it rarely changes.