Route Handlers and APIs
Route Handlers are `route.ts` files that export one function per HTTP method and speak the Web Request/Response APIs. Know their defaults (not cached, params is a Promise, automatic HEAD and OPTIONS), how bodies, cookies and redirects behave, and when to use a handler instead of a Server Action or a direct data call.
Key points
- 1
A
route.tsexports namedGET,POST,PUT,PATCH,DELETE,HEADorOPTIONSfunctions. Other methods get405. Arouteand apagecan't share a segment. - 2
HEADis answered by yourGETwhen not exported, andOPTIONSgets an automatic204with anAllowheader but no CORS headers. - 3
Since v15,
GEThandlers are not cached by default andcontext.paramsis a Promise. Without Cache Components, opt in withdynamic = 'force-static'andrevalidate. With Cache Components, putuse cachein a helper, not in the handler body. - 4
Read a body once with
json(),formData(),text()orarrayBuffer();clone()first if you need it twice. Webhooks must verify the rawtext()before parsing. - 5
redirect()gives307(and keeps cookies set viacookies()),notFound()gives an empty404, and both throw, so call them outsidetry. - 6
Fetch data in Server Components directly, not through your own handlers. Use handlers for public clients, webhooks and non-UI files; Server Actions are queued and meant for UI mutations.
- 7
On serverless hosts there is no shared memory or durable disk, long requests hit
maxDuration, and WebSockets don't work. The Edge Runtime is deprecated in Next.js 16.
Common traps
Re-serialising parsed JSON before checking a webhook signature makes every valid event fail.
A
redirect()insidetry { … } catchis swallowed by the catch block.force-staticdoesn't fail onheaders(); it silently returns empty values and caches them.
Further reading
Suggest a resource- NextResponse reference(opens in a new tab)The helpers NextResponse adds to the Web Response, such as json, redirect and cookies.Docsnextjs.orgEditor’s pick
- MDN: Response(opens in a new tab)The Web Response API that Route Handlers return.Docsdeveloper.mozilla.orgEditor’s pick
- cookies reference(opens in a new tab)Reading and setting cookies in Route Handlers, Server Actions and Server Components.Docsnextjs.orgEditor’s pick
Test yourself on Route Handlers and APIs
Ten questions, with the answer and explanation after each one.