Skip to article content
FrontendXLesson 11 / 20

Route Handlers

A version-qualified path through the Next.js App Router: server components, client boundaries, data fetching, caching layers, streaming, error handling, proxy, images, performance, testing and deployment, with the Next.js 15 and 16 behavior changes called out where they matter.

intermediate · about 45 minutes · 6 exercises

  • Predict
  • Explain
  • Implement
  • Debug
  • Test
  • Interview

What you will be able to do

#
  • Build route.ts endpoints with correct method exports and Web-standard request and response types.
  • Control GET caching explicitly and explain the Next.js 15 default change.
  • Read awaited params in dynamic handlers and choose between handlers and Server Actions.

Overview

#

Endpoints as files

A route.ts file turns its folder into an endpoint. Export functions named after HTTP methods; they receive Web-standard Request and return Response:

snippet.ts
// app/api/products/[id]/route.ts
export async function GET(
  request: Request,
  { params }: { params: Promise<{ id: string }> },
) {
  const { id } = await params;
  const product = await getProduct(id);
  if (!product) return Response.json({ error: 'Not found' }, { status: 404 });
  return Response.json(product);
}

export async function POST(request: Request) {
  const body = await request.json();
  return Response.json({ created: true }, { status: 201 });
}

Supported exports are GET, HEAD, POST, PUT, DELETE, PATCH and OPTIONS. If you do not export OPTIONS, Next.js implements it and sets the Allow header from your other methods. NextRequest and NextResponse from next/server add conveniences like request.nextUrl.searchParams and cookie helpers on top of the standard types.

Caching is explicit

Version-qualified: Route Handlers are not cached by default, and since Next.js 15 that includes GET, which was previously cached by default. Opt a GET handler into caching with export const dynamic = 'force-static'; POST, PUT, DELETE and PATCH are never cached. Under Cache Components the same file follows the page model: a GET handler prerenders when it touches no uncached or runtime data, and uncached data moves into a helper marked use cache because the directive cannot decorate the GET export itself.

Handlers versus actions

Route Handlers are the right surface for webhooks, third-party callers, cron targets and anything that needs explicit HTTP semantics: status codes, headers, content negotiation, caching headers. Server Actions are the right surface for first-party React mutations. Both are public endpoints and both need authentication and validation inside the handler; the file path of a handler is not a capability boundary.

Error behavior

An uncaught throw in a handler produces a 500 with a sanitized message in production. Catch expected failures and return deliberate statuses; reserve thrown errors for the unexpected, and never echo internal error details to clients.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Predict

    In Next.js 15 or 16, which of these handlers are cached by default? // app/api/a/route.ts export async function GET() { ... } // app/api/b/route.ts export const dynamic = 'force-static'; export async function GET() { ... } // app/api/c/route.ts export async function POST() { ... }

    Choose the best answer
  2. Exercise 2Explain

    Your team must expose an endpoint for a payment provider's webhook plus an internal endpoint the React dashboard calls to toggle a flag. Which mechanism for each, and why?

    Reveal the reference answer
    reference.text
    Webhook: a Route Handler. The caller is external, cannot import your actions, and the contract needs explicit HTTP semantics: verify the provider signature header, return 2xx quickly, and return deliberate 4xx/5xx statuses. Dashboard toggle: a Server Action called from the client component, giving typed invocation, pending state via useTransition, and colocated revalidation. The split rule: external callers and HTTP contracts get Route Handlers; first-party UI mutations get Server Actions.

    Authored expected output: Route Handler for the webhook, Server Action for the dashboard toggle, with caller-based reasoning.

    Caller identity is the primary decision input.

  3. Exercise 3Implement

    Implement app/api/revalidate/route.ts with a POST handler that reads a shared secret from the Authorization header, compares it to process.env.REVALIDATE_SECRET, and on success calls revalidateTag(tag, 'max') for the tag given in the JSON body. Return 401 on mismatch and 400 on a missing tag.

    starter.ts
    // app/api/revalidate/route.ts
    // TODO: POST handler with secret check and tag invalidation

    Reveal the reference answer
    reference.ts
    import { revalidateTag } from 'next/cache';
    
    export async function POST(request: Request) {
      const secret = request.headers.get('authorization')?.replace('Bearer ', '');
      if (secret !== process.env.REVALIDATE_SECRET) {
        return Response.json({ error: 'Unauthorized' }, { status: 401 });
      }
      const { tag } = await request.json();
      if (typeof tag !== 'string' || tag.length === 0) {
        return Response.json({ error: 'Missing tag' }, { status: 400 });
      }
      revalidateTag(tag, 'max');
      return Response.json({ revalidated: true });
    }

    Authored expected output: Valid webhook calls invalidate the tag; missing secret or tag returns 401 or 400.

    Webhook handlers need their own auth because the route path is public knowledge.

  4. Exercise 4Debug

    This handler always returns 500 in production and the client sees no useful message. Find the two problems. export async function GET(request: Request, { params }: { params: { id: string } }) { const product = await db.product.findUniqueOrThrow({ where: { id: params.id } }); return Response.json(product); }

    starter.ts
    export async function GET(request: Request, { params }: { params: { id: string } }) {
      const product = await db.product.findUniqueOrThrow({ where: { id: params.id } });
      return Response.json(product);
    }

    Reveal the reference answer
    reference.ts
    Problem one: params is a promise in Next.js 15 and 16, so typing it as a plain object and reading params.id directly throws; it must be awaited. Problem two: findUniqueOrThrow throws on a missing row, producing an unhandled 500; a missing resource should return a deliberate 404. Fixed handler: const { id } = await params; const product = await db.product.findUnique({ where: { id } }); if (!product) return Response.json({ error: 'Not found' }, { status: 404 }); return Response.json(product);

    Authored expected output: Valid ids return the product; unknown ids return 404.

    The async params change and throw-based not-found handling are the two most common handler bugs after upgrading.

  5. Exercise 5Test

    Write a pure function handlerCacheability(method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH', forceStatic: boolean) returning 'cached' only when method is GET and forceStatic is true, 'uncached' otherwise. Assert five cases including POST with forceStatic true (uncached) and GET with forceStatic true (cached).

    starter.ts
    export function handlerCacheability(
      method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH',
      forceStatic: boolean,
    ): 'cached' | 'uncached' {
      // TODO
    }

    Reveal the reference answer
    reference.ts
    export function handlerCacheability(
      method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH',
      forceStatic: boolean,
    ): 'cached' | 'uncached' {
      return method === 'GET' && forceStatic ? 'cached' : 'uncached';
    }
    
    // Non-GET methods are never cached even when the segment config says force-static.

    Authored expected output: All five assertions pass.

    The rule has two conjuncts; tests make the conjunction explicit.

  6. Exercise 6Interview

    An interviewer asks: design the API surface for a blog with public post listing, admin-only publishing, and an image upload. Which App Router mechanisms do you use for each and what do you check at the boundary?

    Reveal the reference answer
    reference.text
    Public listing: a prerendered page reading cached data (use cache with a tag), no endpoint needed unless third parties consume it, in which case a GET Route Handler with force-static or cached reads. Admin publishing: a Server Action from the admin UI with session verification, role check, input validation, and updateTag or revalidateTag('posts', 'max') after the write. Image upload: a POST Route Handler because uploads need raw body handling and explicit response codes; check the session, validate content type and size, stream to storage, and never trust the client-provided filename. Boundary checks everywhere: every mechanism is a public endpoint; auth, authorization, validation and rate limits live inside each one.

    Authored expected output: Three mechanisms chosen by caller and payload shape, with boundary checks enumerated.

    Design questions reward matching mechanism to caller rather than defaulting to one.

Common misconceptions

#
  • GET route handlers are cached by default. Since Next.js 15 they are uncached by default; force-static opts back in.
  • route.ts and page.tsx can coexist in one folder. They conflict; a folder is either UI or an endpoint.
  • Handlers are private because they live in app. Every handler is a public HTTP endpoint and needs its own auth and validation.
  • You must use NextResponse everywhere. Plain Response and Response.json are Web standards and fully supported.

Follow-up practice

#
  • nextjs-request-apis
  • nextjs-server-actions

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.