Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 72 ยท Mutations and Forms

Route Handlers

Build HTTP endpoints in the Next.js App Router with route.ts: GET and POST, Request and Response, dynamic segments, streaming, caching and CORS.

Pages return HTML and Server Actions answer your own forms. But sometimes you need a plain HTTP endpoint: a JSON API for a mobile app, a webhook that a payment provider calls, an RSS feed, an image or a file download, a health check for your load balancer. In the App Router these are called Route Handlers, and you create one by adding a route.ts file to a folder.

A Route Handler is a function that receives a standard web Request and returns a standard web Response. If you know fetch, you already know the objects. This lesson covers the file convention, the HTTP methods, dynamic segments, streaming, caching and CORS.

Real or stand-in? The route.ts code below is real Next.js, shown read-only. The live examples run on the code runner, which has the same web-standard Request, Response, Headers and ReadableStream as the framework (they are built into Node.js), but not the router. A tiny hand-written router stands in for Next.js's file-based matching, so what you see is how the handlers behave, not how Next.js finds them.

The route.ts file

A route.ts (or route.js) file inside the app folder defines an endpoint at the folder's URL. You export one function per HTTP method you support, named in capital letters:

TypeScript
// app/api/hello/route.ts   ->   /api/hello
export async function GET() {
  return Response.json({ message: 'Hello from a route handler' });
}

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

The supported method names are GET, POST, PUT, PATCH, DELETE, HEAD and OPTIONS. If a request arrives with a method you did not export, Next.js answers 405 Method Not Allowed for you. If you do not export OPTIONS, Next.js adds a sensible default one automatically.

A folder cannot contain both a page.tsx and a route.ts at the same level: both want to answer requests for the same URL. Put API endpoints in a folder of their own, commonly under app/api/, though the name api has no special meaning.

Request and Response

Everything uses web standards, so there is little new to learn:

TypeScript
export async function POST(request: Request) {
  const url = new URL(request.url);
  const page = url.searchParams.get('page') ?? '1';       // query string
  const token = request.headers.get('authorization');      // headers
  const data = await request.json();                       // body as JSON
  // or: await request.formData()  /  await request.text()

  return new Response(JSON.stringify({ page, ok: true }), {
    status: 200,
    headers: { 'content-type': 'application/json', 'cache-control': 'no-store' },
  });
}

Response.json(data, init) is a shortcut that sets the JSON content type. Next.js also exports NextRequest and NextResponse, which extend the standard classes with helpers such as request.nextUrl.searchParams and request.cookies (see Cookies and Headers). They are optional: plain Request and Response work fine.

Always treat the incoming body as untrusted, exactly as with actions. Parse it, then validate it with a schema (Validating Input), and answer bad input with a 400 status rather than letting the handler crash.

Dynamic segments

Folder names in square brackets capture parts of the URL, as for pages (Dynamic Routes). In a route handler the captured values arrive in the second argument, and since Next.js 15 params is a Promise you must await:

TypeScript
// app/api/users/[id]/route.ts   ->   /api/users/42
export async function GET(
  request: Request,
  { params }: { params: Promise<{ id: string }> },
) {
  const { id } = await params;
  const user = await db.user.findUnique({ where: { id } });

  if (!user) {
    return Response.json({ error: 'User not found' }, { status: 404 });
  }
  return Response.json(user);
}

Return 404 with a JSON body for missing records instead of the HTML notFound() helper, because API clients expect JSON.

A working stand-in

The stand-in below keeps a small in-memory list of users and a router that maps a URL pattern to a module of method functions, the same shape as real route.ts files. It uses genuine Request and Response objects. Read the output to see statuses, bodies and the automatic 405.

Node.js Route handlers as plain functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Each row is method path status body. The PUT call gets a 405 because the module exports no PUT, and the DELETE answers 204 No Content with an empty body. Note also that a handler is just an async function: you can test it by calling it, with no server at all. We use that idea in Testing Next.js Apps.

Streaming responses

A Response body can be a ReadableStream, so the handler can send data as it becomes available instead of waiting to have everything. This suits long exports, log tails and AI text generation:

TypeScript
// app/api/countdown/route.ts
export async function GET() {
  const encoder = new TextEncoder();

  const stream = new ReadableStream({
    async start(controller) {
      for (let n = 3; n >= 1; n--) {
        controller.enqueue(encoder.encode('T-minus ' + n + '\n'));
        await new Promise((resolve) => setTimeout(resolve, 1000));
      }
      controller.enqueue(encoder.encode('Liftoff\n'));
      controller.close();
    },
  });

  return new Response(stream, {
    headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' },
  });
}

The headers go out first and the browser starts receiving chunks while the function is still running. The stand-in below runs a handler like this and reads the stream the way a client does, one chunk at a time, printing how many bytes each chunk had.

Node.js Reading a streamed response chunk by chunk

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Four separate chunks arrive, each as soon as it was produced. A client that only calls await response.text() would wait for all of them; one that reads the stream can show progress immediately.

Caching of GET handlers

Next.js 15 changed the default: GET handlers are no longer cached automatically, so a handler that reads a database runs on every request, which is what most people expect. You can still opt a GET handler into static output when the response never changes between requests:

TypeScript
// app/api/version/route.ts
export const dynamic = 'force-static';

export async function GET() {
  return Response.json({ version: '1.4.2' });
}

A handler is also treated as dynamic if it reads the request (request.url search parameters, headers, cookies). Other methods (POST and so on) are never cached. With the newer Cache Components model the rules follow the general caching model described in Caching in Next.js: the Big Picture, so check that lesson for your version. When in doubt, set the header yourself: cache-control: no-store for personal or fast-changing data, or public, s-maxage=60 to let a CDN cache a public response.

CORS

Browsers block a web page on one origin from reading API responses from another origin unless the API opts in with CORS headers. Calls from your own pages to your own handlers (same origin) need nothing. If another site or app must call your handler from a browser, send the headers and answer the preflight OPTIONS request that browsers make first:

TypeScript
const corsHeaders = {
  'Access-Control-Allow-Origin': 'https://app.example.com',
  'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
  'Access-Control-Allow-Headers': 'Content-Type, Authorization',
};

export async function OPTIONS() {
  return new Response(null, { status: 204, headers: corsHeaders });
}

export async function GET() {
  return Response.json({ ok: true }, { headers: corsHeaders });
}

Allow specific origins, not *, whenever the endpoint uses cookies or authorization. You can also set headers for many routes at once with the headers option in next.config.ts (see Configuring Next.js).

NextRequest and NextResponse in depth

Plain Request and Response are enough for most handlers, but Next.js adds two subclasses, imported from next/server, with helpers for the jobs you repeat most: reading cookies, changing URLs and building common responses. The same classes are used in the proxy file (Middleware and the Proxy File), so learning them once pays twice.

NextRequest

A NextRequest is a normal Request plus:

  • request.cookies, a small cookie jar for the incoming Cookie header. get(name) returns an object with name and value, or undefined. getAll() returns every cookie, has(name) checks existence, and set, delete and clear change the jar for the rest of the request.
  • request.nextUrl, an extended URL. It has everything a URL has (pathname, searchParams, host) plus Next.js knowledge such as basePath and locale. Its clone() method returns a copy that you can change without touching the original, which is how you build redirect targets.
TypeScript
// app/api/search/route.ts (read-only)
import { NextRequest, NextResponse } from "next/server";

export async function GET(request: NextRequest) {
  const query = request.nextUrl.searchParams.get("q") ?? "";
  const page = Number(request.nextUrl.searchParams.get("page") ?? "1");
  const theme = request.cookies.get("theme")?.value ?? "light";

  return NextResponse.json({ query, page, theme });
}

nextUrl.searchParams is the standard URLSearchParams: get, getAll, has and set all work, and every value is a string, so convert numbers yourself and check the result with Number.isNaN (or validate with a schema, see Validating Input).

NextResponse

NextResponse extends Response with static helpers, and its instances carry a response cookie jar:

Helper What it does
NextResponse.json(body, init) A JSON response with the right content type. Same idea as Response.json.
NextResponse.redirect(url, status) A redirect. The URL must be absolute (use new URL("/login", request.url)). Default status is 307; use 303 after a form post, 308 for permanent.
NextResponse.rewrite(url) Serves another URL's content while keeping the address bar unchanged. Mostly used in the proxy file.
NextResponse.next() Continue to the route. Only meaningful in the proxy file.
TypeScript
// app/api/theme/route.ts (read-only)
import { NextRequest, NextResponse } from "next/server";

export async function POST(request: NextRequest) {
  const { theme } = await request.json();
  if (theme !== "light" && theme !== "dark") {
    return NextResponse.json({ error: "theme must be light or dark" }, { status: 400 });
  }

  const response = NextResponse.json({ theme });
  response.cookies.set("theme", theme, {
    httpOnly: true,
    secure: true,
    sameSite: "lax",
    path: "/",
    maxAge: 60 * 60 * 24 * 365, // one year, in seconds
  });
  return response;
}

export async function DELETE() {
  const response = new NextResponse(null, { status: 204 });
  response.cookies.delete("theme");
  return response;
}

response.cookies.set(name, value, options) writes a Set-Cookie header. The options matter for security: httpOnly hides the cookie from JavaScript, secure sends it only over HTTPS and sameSite: "lax" limits cross-site sending (see Cookies and Headers). delete works by sending the cookie back already expired. A handler may also use the cookies() function from next/headers; response.cookies is handy when you already hold the response object, and request.cookies is the right choice inside the proxy.

Redirects with a cloned URL

To send a visitor somewhere that is a small change of the current URL, clone it, modify it and redirect:

TypeScript
// read-only
const url = request.nextUrl.clone();
url.pathname = "/login";
url.searchParams.set("from", request.nextUrl.pathname);
return NextResponse.redirect(url);

Cloning first matters: request.nextUrl is shared for the request, and changing it in place could affect code that runs later. The stand-in below implements small versions of these helpers on top of the real Request, Response and URL classes that Node provides, then runs three requests through a handler. It is a model of the API shape, not the Next.js implementation.

Node.js A mini NextRequest and NextResponse

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first request has no session cookie, so the handler answers with a redirect to /login?from=%2Faccount (built from a clone; %2F is the encoded slash). The second has the cookie and gets through. The third shows Set-Cookie being produced with the security options, and the fourth shows input validation returning a 400.

Route Handler or Server Action?

Choose a Route Handler when something outside your own UI needs to call you (other apps, webhooks, scripts), when you need control over the status code, headers or body format, when you serve non-HTML such as files, feeds or streams, or when you want a stable, documented URL. Choose a Server Action for mutations triggered by your own forms and buttons, where the framework handles the wiring and refreshes the page for you. For reads in your own pages, skip both: fetch directly in a Server Component (Fetching Data in Server Components) instead of calling your own API over HTTP.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How do you define a POST endpoint at /api/orders in the App Router?

    Route handlers live in route.ts files and export one function per HTTP method, named in capital letters.
  2. 2. In a dynamic route handler such as app/api/users/[id]/route.ts, how do you read the id?

    Dynamic values arrive in the second argument as params, which is a Promise in Next.js 15 and later.
  3. 3. What status does Next.js return if a request uses a method your route.ts does not export?

    Unsupported methods get 405 automatically.
  4. 4. Are GET route handlers cached by default in Next.js 15 and later?

    The default changed to uncached so that handlers reading live data behave as expected. Static output is opt-in.
  5. 5. When do you need to add CORS headers to a route handler?

    Same-origin calls need nothing. Cross-origin browser calls need Access-Control headers and a response to the preflight OPTIONS request.

Summary

  • A route.ts file turns a folder into an HTTP endpoint; export GET, POST, PUT, PATCH, DELETE, HEAD or OPTIONS functions.
  • Handlers use standard web Request and Response (plus optional NextRequest and NextResponse helpers); unsupported methods get 405.
  • Dynamic folder names deliver params in the second argument, as a Promise to await.
  • A ReadableStream body streams data to the client as it is produced.
  • GET handlers are uncached by default; opt into static output with dynamic = 'force-static' or control caching with headers.
  • Add CORS headers and an OPTIONS handler only when other origins must call from a browser.
  • Use handlers for external callers and non-HTML output, and Server Actions for your own forms.

Next: Cookies and Headers