What is the route.js file in the App Router?

route.js (or route.ts) is the App Router file convention for Route Handlers: server-side HTTP endpoints. Its exported functions (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS) handle requests to the folder's URL and return Web Response objects.

Where it fits

  • app/api/orders/route.ts serves /api/orders.
  • It can live anywhere in app/, not just under api/, such as app/feed.xml/route.ts for an RSS feed or app/auth/callback/route.ts for OAuth.
  • It cannot coexist with page.tsx in the same folder, because both would claim the URL.

Parameters

  1. request: a NextRequest with nextUrl, cookies, headers and body methods.
  2. context: { params: Promise<...> }. Type it with the generated RouteContext<'/api/orders/[id]'>.

Segment config it supports

dynamic, revalidate, fetchCache (previous model only), dynamicParams, preferredRegion and maxDuration. With Cache Components, GET handlers are prerendered when possible, and request-dependent parts run at request time.

Special generated routes

Metadata files like sitemap.ts, robots.ts, opengraph-image.tsx and manifest.ts are specialized Route Handlers that Next.js recognizes by name.

vs Server Functions

Use route.ts when an external client calls the endpoint, when you need control over HTTP (status codes, headers, streaming, non-JSON bodies), or for GET requests. Use Server Functions for form submissions and mutations from your own React UI.

Code example

tsx
1// app/feed.xml/route.ts - an RSS feed served at /feed.xml
2import { cacheLife } from "next/cache";
3import { getPosts } from "@/lib/posts";
4
5async function buildFeed() {
6 "use cache";
7 cacheLife("hours");
8 const posts = await getPosts();
9 const items = posts
10 .map((p) => `<item><title>${p.title}</title><link>https://acme.dev/blog/${p.slug}</link></item>`)
11 .join("");
12 return `<?xml version="1.0"?><rss version="2.0"><channel><title>Acme</title>${items}</channel></rss>`;
13}
14
15export async function GET() {
16 return new Response(await buildFeed(), {
17 headers: { "Content-Type": "application/rss+xml; charset=utf-8" },
18 });
19}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.

Open in study app