Skip to content
BackendChapter 19 / 34Intermediate5 min read

Route Handlers (API)

Learn how to build a REST API in app/api with Next.js route handlers, using the Web Request and Response, dynamic params, auth checks and caching.

On this page

1. What are Route Handlers?

In the Pages Router these were called API Routes. In the App Router, you create a route.ts anywhere inside the app folder and it becomes an API endpoint, for example app/api/products/route.ts gives you /api/products.

A Route Handler does not render any UI. It returns JSON, text, a file or a redirect.

2. Why does it matter?

Server Actions are only for the forms of your own app. But sometimes the outside world also needs to talk to your server: a mobile app, a webhook, another website.

Server ActionRoute Handler
Called only from your own Next.js appAny client can call it
POST only, URL hiddenGET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS
For forms and mutationsPublic API, webhooks, file downloads
The response updates the UIThe response is JSON or any format

3. Where is it used?

Use caseExample route
API for a mobile appapp/api/products/route.ts
Stripe or CMS webhookapp/api/webhooks/stripe/route.ts
File download or CSV exportapp/api/reports/route.ts
OAuth callbackapp/api/auth/callback/route.ts
RSS feedapp/feed.xml/route.ts

4. How does it work?

Route Handler flow
The client sends an HTTP request
Next.js finds route.ts from the URL
The function named after the method runs
Auth check + validation + the work
Response.json is returned

Some important rules:

RuleDetail
File nameAlways route.ts or route.js
ConflictA single segment cannot have both page.tsx and route.ts
Unknown methodNext.js returns 405 Method Not Allowed by itself
CachingNo caching by default, it runs on every request
Paramsctx.params is a Promise, so you must await it

5. Code example

Example 1: list and create

ts
import { db } from "@/lib/db";
import { getSession } from "@/lib/dal";

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const category = searchParams.get("category") ?? undefined;

  const products = await db.product.findMany({ where: { category } });
  return Response.json(products);
}

export async function POST(request: Request) {
  const session = await getSession();
  if (!session) {
    return Response.json({ error: "Please log in" }, { status: 401 });
  }

  const body = await request.json();
  const product = await db.product.create({ data: { name: String(body.name) } });
  return Response.json(product, { status: 201 });
}

Example 2: dynamic segment app/api/products/[id]/route.ts

ts
import type { NextRequest } from "next/server";
import { db } from "@/lib/db";

export async function GET(_request: NextRequest, ctx: RouteContext<"/api/products/[id]">) {
  const { id } = await ctx.params;
  const product = await db.product.findUnique({ where: { id } });

  if (!product) {
    return Response.json({ error: "Product not found" }, { status: 404 });
  }

  return Response.json(product);
}

How does the code work?

PartMeaning
export async function GETGET /api/products runs this function
new URL(request.url)The standard way to read the query string
request.json()Parses the POST body as JSON
Response.json(data, { status })A JSON response with a status code
RouteContext<"/api/products/[id]">Next.js's global type helper, makes params typed
await ctx.paramsIn Next.js 16, params are async

When Cache Components is on, a static GET handler can be prerendered. If you want to cache data, put "use cache" in a separate helper function, not inside the handler.

Interview tip

"Server Action or Route Handler?" Answer: a Server Action for the forms and mutations of your own app, and a Route Handler for outside clients, webhooks and non-HTML responses.

6. Common mistakes

Mistake: Keeping both page.tsx and route.ts in the same folder

Why? Both claim the same URL, and Next.js gives a conflict error.

Better: Keep the API in a separate segment, such as inside app/api/...

Mistake: Fetching your own API from your own Server Component

Why? It adds an extra network hop and causes URL issues in a production build.

Better: Call the database or a service function directly in the Server Component.

Mistake: Thinking a Route Handler is protected because the UI has no link to it

Why? Every route.ts is a public URL, and anyone can hit it with curl.

Better: Check the session and role in every handler, and return 401 or 403.

Mistake: Using the request body without validating it

Why? Wrong types or missing fields turn into database errors or security bugs.

Better: safeParse the body with a Zod schema and return 400 if it fails.

7. What to learn before and after

Final quick revision

PointDetail
Fileapp/api/.../route.ts
FunctionsGET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS
InputWeb Request or NextRequest
OutputResponse.json(data, { status })
Paramsawait ctx.params
SecurityAn auth check in every handler