Course map
Stage 1: App Router Foundations
Stage 2: The Rendering Model
Stage 3: Data, Caching and Mutations
Stage 4: Full-Stack Next.js
Stage 5: Production and Specialization

Part 13 / Stage 4

Route Handlers

Goal: Write a route.ts file under app/api/... and answer, with real requests and real framework behavior (not a guess), the question every full-stack Next.js route eventually asks: is this a Route Handler or a Server Action? Built on the PNR-status universe Parts 8–9 already taught (app/status/[pnr]/page.tsx, app/status/lib/pnr.ts) — this part gives that same lookup a JSON twin, plus a webhook endpoint no browser form ever calls, which is exactly the shape that makes a Route Handler the right tool instead of a Server Action. Time: ~6 h · Level: finished Part 12 (Server Actions and forms) Verified against: Next.js 16.4.6 / React 19.3.0, cacheComponents: true + partialPrefetching: true — this install's defaults since create-next-app, confirmed in TOOLING.md.

What you will learn

  • The route.ts file convention: where it can live, which HTTP methods it can export, and why it can never sit at the same route segment as a page.tsx
  • Reading a request with the plain Web Request object (request.json(), request.url + the standard URL/searchParams API) — no Next.js-specific type required for the simple case
  • Returning a response with the plain Web Response object (Response.json(body, { status })) and when NextRequest/NextResponse actually add something the plain Web APIs don't
  • Typing a dynamic route's params with the generated RouteContext<'/path/[param]'> helper
  • What happens automatically when a Route Handler file doesn't export the HTTP method a client used — a real 405, not a crash
  • How Cache Components classifies a GET Route Handler as static or dynamic, using the installed docs' own three worked examples, each reproduced for real against this harness
  • A decision rule for "Route Handler or Server Action", backed by the installed docs' own stated purpose for each, not a rule of thumb invented for this course

Topics in this part

Practice

Every exercise adds a scratch route under harness/app/api/scratch-*/, runs a real command against it, and then removes what it added (rm -rf the scratch directory) before moving on. Copy the exact commands you ran and their real output into your own notes; do not type output from memory — status codes and headers for automatically-generated responses (HEAD, OPTIONS, 405) are exactly the kind of detail that's easy to guess wrong.


Exercise 1: HEAD and OPTIONS, generated for free from a GET-only route

Scenario: Section 4's README only showed DELETE on a route with no exports at all (a true 405). A route that exports only GET is a more interesting case — HEAD and OPTIONS are both legal HTTP methods, and neither one is exported anywhere in this part's files. What to do: Reuse app/api/status/[pnr]/route.ts as-is (no scratch route needed) and send it a HEAD request, then an OPTIONS request. Read the real status codes and the real allow header.

Sample output (run for real against this course's harness):

$ curl -s -D - -o /dev/null -X HEAD http://localhost:PORT/api/status/2458001234
HTTP/1.1 200 OK
content-type: application/json
$ curl -s -D - -o /dev/null -X OPTIONS http://localhost:PORT/api/status/2458001234
HTTP/1.1 204 No Content
allow: GET, HEAD, OPTIONS

💡 Hint: Neither response came from any code you or this course's harness wrote — the file exports exactly one function, GET. Next.js derives HEAD from GET automatically (same status and headers, no body) and generates a default OPTIONS response listing every method the route actually supports, read straight off the file's own exports.


Exercise 2: The old dynamic route config export, under Cache Components

Scenario: The installed route-handlers.md guide shows export const dynamic = 'force-static' as the pre-Cache-Components way to opt a GET handler into caching. This install has Cache Components on by default (section 6 already showed a handler with no dynamic reads prerenders on its own, with no config at all) — check whether the old config export still works alongside it. What to do: Create app/api/scratch-static/route.ts with export const dynamic = 'force-static'; plus a plain GET returning Response.json({ ok: true }) — no dynamic reads at all, the same shape as app/api/ops/ping/route.ts. Run npm run build and read the real error.

Sample output (run for real against this course's harness):

$ npm run build
...
Error: Turbopack build failed with 1 error:
./app/api/scratch-static/route.ts:1:14
Error: Route segment config "dynamic" is not compatible with `nextConfig.cacheComponents`. Please remove it.

💡 Hint: Not redundant — actively incompatible. The pre-Cache-Components route segment config (dynamic, revalidate, fetchCache, etc.) was superseded by the "use cache" model Part 10 already taught; this install's own build refuses to start if a route file still carries the old config export. /api/ops/ping/route.ts gets the exact same static result with no config export at all, which is the actual fix: delete the dynamic line entirely rather than change its value.


Exercise 3: An uncaught error inside a dynamic GET handler — a real 500, not a build failure

Scenario: A handler that always throws is a reasonable thing to want to test — but try it on a handler with no dynamic reads first, and see what actually happens. What to do: First, create app/api/scratch-throw/route.ts with just export async function GET() { throw new Error("boom"); } and run npm run build. Read the real error. Then fix it by forcing the handler to be dynamic (await headers() before the throw), rebuild, start, and hit it with curl.

Sample output — first attempt, build time (run for real against this course's harness):

$ npm run build
...
Export encountered an error on /api/scratch-throw/route: /api/scratch-throw, exiting the build.
⨯ Next.js build worker exited with code: 1 and signal: null

Sample output — after adding await headers(), at request time:

$ curl -s -D - http://localhost:PORT/api/scratch-throw
HTTP/1.1 500 Internal Server Error

Server log:

⨯ Error: boom from scratch-throw

💡 Hint: A handler with no dynamic reads is eligible for build-time prerendering (section 6) — and prerendering it means actually running it during next build. A handler that always throws fails the build itself, with a very different error than a runtime 500. Forcing the handler to be dynamic (any runtime API read, same mechanism section 6 used for /api/ops/now) defers that same throw to request time instead, where it becomes an ordinary 500 and the production response body doesn't leak the real error message — only the server's own log does.


Exercise 4: RouteContext vs. reading params with no type at all

Scenario: Section 2 used the generated RouteContext<'/api/status/[pnr]'> helper. Confirm what breaks (or doesn't) without it. What to do: Create app/api/scratch-params/[id]/route.ts with a GET that destructures context.params with no type annotation at all (export async function GET(request: Request, context) { ... }, using plain JS-style typing or any), and confirm it still runs correctly at runtime, then check what tsc/the editor reports.

Sample output (run for real against this course's harness):

$ curl -s http://localhost:PORT/api/scratch-params/abc123
{"id":"abc123"}

💡 Hint: It runs fine either way — RouteContext is a compile-time convenience generated into .next/types/ (Part 1's "typed routes" finding, Part 2's PageProps equivalent for pages), not something the running JavaScript needs. Without it, TypeScript can't catch a typo in the route's own dynamic segment name at compile time; with it, mistyping context.params.pnr as context.params.pnrr is a build-time type error instead of a silent undefined at runtime.


Exercise 5: A POST route with no Content-Type header at all

Scenario: Section 3's delay route always sent -H "Content-Type: application/json". Real external callers sometimes don't bother. Confirm whether request.json() actually needs that header to work. What to do: Reuse app/api/status/[pnr]/delay/route.ts as-is. Send the exact same valid JSON body as section 3, but omit the Content-Type header entirely.

Sample output (run for real against this course's harness):

$ curl -s -X POST http://localhost:PORT/api/status/2458001234/delay -d '{"minutes": 7}'
{"updated":true,"record":{...,"delayMinutes":7}}

💡 Hint: It works — request.json() parses the body's actual bytes as JSON regardless of the Content-Type header the client happened to send (or not send); the header is metadata the caller is supposed to set accurately, not something request.json() itself checks before parsing. Don't rely on Content-Type as a validation step — validate the actual parsed shape, exactly as this part's delay route already does for minutes.


Next

Part 14: Middleware and the request pipeline

Show the solutions for Part 13 (5 files)

solutions/ex01.md

# Solution to Exercise 1

No new file needed — `app/api/status/[pnr]/route.ts` (this part's own
`GET`-only route) is enough on its own.

**`HEAD`, run for real against this harness:**
```text
$ curl -s -D - -o /dev/null -X HEAD http://localhost:PORT/api/status/2458001234
HTTP/1.1 200 OK
content-type: application/json
```

**`OPTIONS`, run for real:**
```text
$ curl -s -D - -o /dev/null -X OPTIONS http://localhost:PORT/api/status/2458001234
HTTP/1.1 204 No Content
allow: GET, HEAD, OPTIONS
```

The route file exports exactly one function (`GET`). Next.js derives a
correct `HEAD` response (same status/headers the matching `GET` would
produce, body stripped) automatically, and generates a default `OPTIONS`
response whose `allow` header lists every method the file actually
supports — `GET` (the one export), plus `HEAD` and `OPTIONS` themselves,
since both are always implied once any method exists. None of this is
code this course's harness wrote.

solutions/ex02.md

# Solution to Exercise 2

```ts
// app/api/scratch-static/route.ts (scratch — created, built, then deleted)
export const dynamic = 'force-static';

export async function GET() {
  return Response.json({ ok: true });
}
```

**Build, run for real against this harness:**
```text
$ npm run build
...
Error: Turbopack build failed with 1 error:
./app/api/scratch-static/route.ts:1:14
Error: Route segment config "dynamic" is not compatible with `nextConfig.cacheComponents`. Please remove it.
```

The old route segment config exports (`dynamic`, `revalidate`,
`fetchCache`, and friends — the pre-Cache-Components caching vocabulary)
are not just unnecessary once `cacheComponents: true` is set, this
install's own build **rejects** them outright with a named, specific
error. `app/api/ops/ping/route.ts`, which gets the exact same `○` static
result in the real build, carries no config export of any kind — that is
the actual migration: delete the old `dynamic` line, don't try to keep it
set to a "safe" value. Scratch file removed with `rm -rf
app/api/scratch-static` after this check, and `npm run build` re-run
clean to confirm nothing was left behind.

solutions/ex03.md

# Solution to Exercise 3

**First attempt — a handler with no dynamic reads, run for real:**
```ts
// app/api/scratch-throw/route.ts (scratch, attempt 1)
export async function GET() {
  throw new Error("boom");
}
```
```text
$ npm run build
...
Export encountered an error on /api/scratch-throw/route: /api/scratch-throw, exiting the build.
⨯ Next.js build worker exited with code: 1 and signal: null
```
`npm run build` itself fails — it never gets to produce a route table at
all. A `GET` handler with no uncached/runtime data reads is eligible for
build-time prerendering (Part 13's section 6), and prerendering means
Next.js actually *invokes* the handler during the build to capture its
output. A handler that always throws fails that invocation, and the
build aborts.

**Fix — force the handler to be dynamic, then rebuild and run for real:**
```ts
// app/api/scratch-throw/route.ts (scratch, attempt 2)
import { headers } from "next/headers";

export async function GET() {
  await headers(); // forces dynamic — deferred to request time
  throw new Error("boom from scratch-throw");
}
```
```text
$ npm run build
...
├ ƒ /api/scratch-throw
```
```text
$ npm run start -p PORT
$ curl -s -D - http://localhost:PORT/api/scratch-throw
HTTP/1.1 500 Internal Server Error
```
Server log:
```text
⨯ Error: boom from scratch-throw
```

Reading a runtime API before the `throw` defers the handler's execution
to request time instead of build time, exactly like Part 8/9's
dynamic-vs-static Server Component split. At request time the same
uncaught error becomes a plain `500`, and — confirmed by reading the
actual response body in the `curl` output above — the real error message
("boom from scratch-throw") does **not** leak into the production
response; it only appears in the server's own log. Scratch route removed
with `rm -rf app/api/scratch-throw` after this check.

solutions/ex04.md

# Solution to Exercise 4

```ts
// app/api/scratch-params/[id]/route.ts (scratch — created, run, then deleted)
export async function GET(request: Request, context: { params: Promise<{ id: string }> }) {
  const { id } = await context.params;
  return Response.json({ id });
}
```
(`context` is written here with an inline object type rather than `any` —
TypeScript's `strict` mode, on in this harness's `tsconfig.json`, rejects
an implicit `any` parameter outright. `RouteContext<'/api/scratch-params/[id]'>`
is the generated shorthand for exactly this shape; this file spells the
shape out by hand instead, to see whether the *behavior* differs.)

**Run for real against this harness:**
```text
$ curl -s http://localhost:PORT/api/scratch-params/abc123
{"id":"abc123"}
```

It behaves identically to the `RouteContext`-typed version in
`app/api/status/[pnr]/route.ts`. `RouteContext<'/path/[param]'>` is a
compile-time convenience generated into `.next/types/` during `next dev`
or `next build` (the same "typed routes" mechanism `TOOLING.md` already
documented for `PageProps`) — it exists purely so a typo in the dynamic
segment's name (`context.params.pnrr` instead of `context.params.pnr`)
is a build-time type error instead of a silent `undefined` discovered
only at runtime. Dropping it loses that compile-time guarantee but
changes nothing about what actually runs. Scratch route removed with
`rm -rf app/api/scratch-params` after this check.

solutions/ex05.md

# Solution to Exercise 5

Uses `app/api/status/[pnr]/delay/route.ts` as-is — the only difference
from section 3's request is one missing header.

**Request, run for real against this harness:**
```text
$ curl -s -X POST http://localhost:PORT/api/status/2458001234/delay -d '{"minutes": 7}'
{"updated":true,"record":{"pnr":"2458001234","train":"Karnataka Express","trainNumber":"12627","from":"Bengaluru Cantt","to":"Chennai Central","status":"Confirmed","coach":"B2","seat":"34","delayMinutes":7}}
```

No `Content-Type` header was sent at all, and the request still
succeeded exactly like section 3's version that did send
`Content-Type: application/json`. `request.json()` parses whatever bytes
are actually in the request body as JSON — it doesn't consult the
`Content-Type` header first to decide whether to try. The header is
metadata the caller is supposed to set accurately for *other* consumers
(browsers, proxies, logging) to rely on; it is not something this
handler's own parsing step checks. The real validation this route
performs — rejecting a non-numeric or negative `minutes` (section 3's
`-5` example) — has nothing to do with headers at all, which is exactly
why relying on `Content-Type` as a stand-in for validation would have
been the wrong instinct in the first place.

Common mistakes

Mistake Why it is wrong Fix
Putting a route.ts at the same segment as a page.tsx The installed docs state this directly as a conflict — one file would have to take over every HTTP verb for that route, and the other couldn't exist Nest the route under a sibling segment (this part uses api/ as that sibling, the framework's own convention)
Assuming an unsupported HTTP method on a route file will crash or silently do nothing Next.js intercepts it and returns a real 405 before the handler's own code runs — verified directly in section 4 Export every method the route actually needs to support; rely on the automatic 405 for the rest
Building a Route Handler for a mutation only this app's own form ever calls That is exactly what a Server Action already is (Part 12) — a Route Handler adds a URL, a method, and manual body-parsing for no benefit Use a Server Action when the caller is always this app's own rendered UI; reach for a Route Handler when it isn't
Trying to write "use cache" directly inside a GET handler's body The installed docs state this doesn't work inside a Route Handler body at all Extract the cached work into a separate helper function and call it from the handler, same as Part 10's Server Component pattern
Trusting request.json() to always succeed because "the client sends JSON" An external caller (a webhook, a misconfigured script) can send anything — section 3's curl -d 'not json' reproduces exactly this Wrap the parse in try/catch and return a 400 on failure, as this part's delay route does
Forgetting a Route Handler is reachable by anyone, not just this app's own pages Section 5's whole decision rule rests on this — "public HTTP endpoint" is not a figure of speech Treat every Route Handler as an untrusted entry point, exactly like Part 12 already said about every Server Action

Quick recap

  • A route.ts file under app/ defines a Route Handler with named exports per HTTP method (GET, POST, ...); it can live anywhere a page can, except at the same segment as one.
  • The plain Web Request/Response objects are enough for most handlers — request.json(), new URL(request.url).searchParams, Response.json(body, { status }) — with RouteContext<'/path/[param]'> as the one Next.js-specific addition for typed dynamic params.
  • An HTTP method a route file doesn't export gets a real 405, generated by the framework with zero code written for it.
  • The decision between a Route Handler and a Server Action comes straight from the installed docs' own stated purpose for each: a Server Action is for mutating data from this app's own frontend; a Route Handler is a public HTTP endpoint any client can reach.
  • Cache Components classifies a GET Route Handler exactly like a Server Component — no dynamic/uncached data reads it static (and this part proved the body is genuinely baked into .next/server/...); a runtime API (headers(), cookies(), connection()) makes it dynamic; "use cache" has to live in a helper function, never directly in the handler body.
  • Every Route Handler is reachable by anyone who knows its path and method — the same "treat it as untrusted" rule Part 12 gave Server Actions applies here too, just earned from a different installed doc.

Checklist

  • I wrote a GET Route Handler using only the plain Web Request/Response objects and read its JSON response with curl.
  • I wrote a POST Route Handler that parses a JSON body, validates it by hand, and returns a 400 on both malformed JSON and a value that fails validation — all reproduced with real curl output, not assumed.
  • I hit a route file with an HTTP method it doesn't export and got a real 405 with no code of my own producing it.
  • I can state, from the installed docs' own wording, why a given mutation belongs in a Server Action versus a Route Handler.
  • I built one static and one dynamic GET Route Handler under cacheComponents: true, confirmed their ○/ƒ classification in a real next build route table, and confirmed the static one's body was actually baked into .next/server/... at build time.

Search the guide