Build a production-shaped app

Add a Route Handler

Expose an HTTP endpoint with the Web Request and Response APIs and choose it only when the application needs a real protocol boundary.

8 minute lesson

~~~

A route.ts file inside app handles HTTP methods such as GET and POST. It is the App Router equivalent of an API route.

Use Route Handlers for webhooks, public APIs, downloads, feeds, or clients that cannot call a Server Action. Do not make a Server Component call your own Route Handler just to reach the same server-side data function; call the shared function directly. A route file cannot coexist with a page file at the same segment.

Each exported method receives the standard Web Request object and returns a standard Response. This makes the protocol boundary visible: parse and authenticate the request, call trusted application code, then translate the result into an HTTP status, headers, and body. Unsupported methods receive 405 Method Not Allowed.

// app/api/health/route.ts
export async function GET() {
  return Response.json(
    { ok: true, checkedAt: new Date().toISOString() },
    { headers: { 'Cache-Control': 'no-store' } },
  )
}

A GET handler is not automatically a promise of static or cached data. Its behavior depends on the APIs it uses and, with Cache Components, whether you deliberately cache the underlying work. Make freshness part of the endpoint contract.

For a webhook, verify the signature against the raw body before parsing or mutating anything. For an authenticated API, authorize the specific resource rather than merely checking for a session. Return stable public error codes, not stacks or database messages.

Add the health route and inspect its status, content type, and cache header with curl. Send POST too and confirm it receives 405. The handler should call shared server code directly instead of making a loopback request.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →