Nextjs Fundamentals · Data Fetching

Route Handlers

`route.ts` over `Request`/`Response`

Route Handlers

A Route Handler lets you build an HTTP endpoint inside the app directory. You define it in a route.ts file and export a function named after the HTTP method, receiving a Web Request and returning a Web Response:

// app/api/hello/route.ts
export async function GET(request: Request) {
  return Response.json({ message: 'Hello' });
}

Route Handlers use the standard Web Request/Response APIs, which Next.js extends with NextRequest and NextResponse for conveniences. The supported methods are GET, POST, PUT, PATCH, DELETE, HEAD, and OPTIONS; any other method returns 405 Method Not Allowed.

They behave much like page.tsx files: they can be nested anywhere under app, but you cannot place a route.ts at the same route segment as a page.tsx — each segment is either a page or a route, not both. They also do not participate in layouts or client-side navigation.

By default, Route Handlers are not cached; only GET can opt into caching, for example with export const dynamic = 'force-static'. With Cache Components, a GET handler follows the same model as a UI route — prerendered when it touches no uncached data, request-time otherwise.

You are about to answer a short quiz on route.ts over Request/Response.

  1. A Route Handler is defined in a route.ts file inside the app directory.
  2. A Route Handler receives a Web ___ and returns a Web Response.
  3. You can place a route.ts file at the same route segment as a page.tsx file.
  4. An unsupported HTTP method on a Route Handler returns status ___ Method Not Allowed.
  5. Route Handlers are cached by default.
  6. Only the ___ method can opt into caching for a Route Handler.