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.tsserves/api/orders.- It can live anywhere in
app/, not just underapi/, such asapp/feed.xml/route.tsfor an RSS feed orapp/auth/callback/route.tsfor OAuth. - It cannot coexist with
page.tsxin the same folder, because both would claim the URL.
Parameters
request: aNextRequestwithnextUrl,cookies,headersand body methods.context:{ params: Promise<...> }. Type it with the generatedRouteContext<'/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
1// app/feed.xml/route.ts - an RSS feed served at /feed.xml2import { cacheLife } from "next/cache";3import { getPosts } from "@/lib/posts";45async function buildFeed() {6 "use cache";7 cacheLife("hours");8 const posts = await getPosts();9 const items = posts10 .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}1415export 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.