🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Route Handlers: Building APIs in Next.js

Next.js BackendđŸŸĸ Free Lesson

Route Handlers: Building APIs in Next.js

A Next.js application can own its own backend without standing up a second service. The App Router treats a route.js file as the API counterpart of a page.js: same folder, same dynamic segments, different contract. Instead of rendering HTML, route handlers receive standard Web Request objects and return Response objects — which means the skills transfer directly to Cloudflare Workers, Deno, and any Fetch-API runtime.

This lesson moves past the hello-world handler. You will see how method exports map to verbs, how to read dynamic params and query strings safely, how to validate and parse bodies, how to stream responses for long-running work, and how to structure handlers so authentication, error handling, and caching behave predictably in production.

Prerequisites

  • !App Router fundamentals and file conventions
  • !Comfort with async JavaScript and JSON
  • !Basic understanding of HTTP status codes and headers

What You'll Learn

  • 1Export GET, POST, PATCH, and DELETE handlers from one route file
  • 2Parse params, query strings, and request bodies with correct types
  • 3Return typed Response objects and handle errors uniformly
  • 4Stream results and apply caching headers where appropriate

One file, every verb

Each HTTP method is a named export. Anything you do not export returns 405 automatically, which is a useful default — an API that silently accepts every verb is an API that is harder to secure. Dynamic segments use the same bracket syntax as pages, and the second argument carries the resolved params.

// app/api/products/route.js
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { db } from '@/lib/db';

const ProductCreate = z.object({
  name: z.string().min(2).max(120),
  priceCents: z.number().int().positive(),
  category: z.string(),
});

export async function GET(request) {
  const { searchParams } = new URL(request.url);
  const category = searchParams.get('category');
  const limit = Math.min(Number(searchParams.get('limit')) || 20, 100);

  const products = await db.product.findMany({
    where: category ? { category } : undefined,
    take: limit,
    orderBy: { createdAt: 'desc' },
  });

  return NextResponse.json({ products, count: products.length });
}

export async function POST(request) {
  let body;
  try {
    body = await request.json();
  } catch {
    return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 });
  }

  const parsed = ProductCreate.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json(
      { error: 'Validation failed', issues: parsed.error.issues },
      { status: 422 }
    );
  }

  const product = await db.product.create({ data: parsed.data });
  return NextResponse.json(product, { status: 201 });
}

Two details carry weight here. new URL(request.url) is how you reach the query string on a raw Request — Next.js does not hand you a parsed object. And validation returns 422 with structured issues rather than a generic 400, so client forms can highlight the exact fields that failed. Keeping the schema next to the handler, rather than in a shared package imported by four services, also makes review of a breaking change a single-file diff.

Dynamic segments and typed params

Individual resources live in a sibling folder with a bracketed param. In recent Next.js versions params are a Promise in Server Components and route handlers alike, so awaiting them is mandatory rather than optional:

// app/api/products/[id]/route.js
import { NextResponse } from 'next/server';
import { db } from '@/lib/db';

export async function GET(request, { params }) {
  const { id } = await params;
  if (!/^[0-9a-f-]{36}$/.test(id)) {
    return NextResponse.json({ error: 'Malformed id' }, { status: 400 });
  }

  const product = await db.product.findUnique({ where: { id } });
  if (!product) {
    return NextResponse.json({ error: 'Not found' }, { status: 404 });
  }
  return NextResponse.json(product);
}

export async function PATCH(request, { params }) {
  const { id } = await params;
  const patch = await request.json();
  const product = await db.product.update({ where: { id }, data: patch });
  return NextResponse.json(product);
}

export async function DELETE(request, { params }) {
  const { id } = await params;
  await db.product.delete({ where: { id } });
  return new NextResponse(null, { status: 204 });
}

Note the id format check before the database call. It is not a security boundary on its own, but it rejects garbage early and keeps malformed keys out of your query logs. Returning 404 for an unknown id — rather than letting a "record not found" exception surface as a 500 — keeps client retry logic honest and monitoring signals clean.

Status codes and errors that clients can trust

A handler is a contract. The table below is the mapping most REST clients expect, and sticking to it saves your front-end team a surprising amount of debugging:

SituationStatusBody shape
Successful read or write200Resource or collection
Resource created201Created resource with Location header
Successful delete with no body204Empty
Malformed JSON or bad query400{ error: string }
Missing or invalid credentials401{ error: string }
Authenticated but forbidden403{ error: string }
Unknown resource id404{ error: string }
Schema validation failure422{ error, issues[] }
Unexpected server fault500Generic message, details to logs only

Returning raw exception messages from a 500 leaks internals. Log the stack on the server, return a correlation id, and let support trace it.

Streaming responses and long work

Not every endpoint returns a single JSON blob. An export that streams tokens from a model, tails a log, or aggregates many shards can return a ReadableStream directly, and the client starts receiving bytes before the handler finishes:

// app/api/chat/route.js
export async function POST(request) {
  const { prompt } = await request.json();

  const encoder = new TextEncoder();
  const stream = new ReadableStream({
    async start(controller) {
      const reply = await streamModelReply(prompt);
      for await (const chunk of reply) {
        controller.enqueue(encoder.encode(chunk.text));
      }
      controller.close();
    },
  });

  return new Response(stream, {
    headers: {
      'Content-Type': 'text/plain; charset=utf-8',
      'Cache-Control': 'no-store',
    },
  });
}

Because this response is per-user and uncacheable, no-store is explicit. If you forget it, proxies may happily buffer and cache part of a private stream — a subtle and embarrassing leak.

Caching GET handlers

GET route handlers can be cached at request time when they use no dynamic APIs, but most real handlers read cookies or headers and therefore render per request. When a GET is genuinely static — a public price list, a feature flag snapshot — set revalidate or explicit Cache-Control headers so the CDN absorbs the traffic instead of your database.

// app/api/feature-flags/route.js
import { NextResponse } from 'next/server';

export const revalidate = 300;

export async function GET() {
  const flags = await loadFlags();
  return NextResponse.json(flags, {
    headers: { 'Cache-Control': 's-maxage=300, stale-while-revalidate=600' },
  });
}

Handlers versus Server Actions

Route handlers and Server Actions both run on the server, but they answer different questions. Reach for a route handler when the caller is not your own React tree: mobile apps, webhooks from Stripe or GitHub, partner integrations, or any client that speaks plain HTTP. Reach for a Server Action when the caller is a form or event handler inside your app and you want progressive enhancement without writing fetch code. Confusing the two leads to teams bolting fetch calls onto every mutation when a form action would have been three lines.

Collections, pagination, and filtering

Collection endpoints deserve more design attention than they usually get. Returning an unbounded array works in a demo and fails in production the day a table crosses a hundred thousand rows. Prefer explicit pagination — cursor-based for infinite scroll feeds, offset-based for admin tables where page numbers matter — and encode the contract in the response so clients never guess.

// app/api/products/route.js — cursor pagination
import { NextResponse } from 'next/server';
import { db } from '@/lib/db';

export async function GET(request) {
  const { searchParams } = new URL(request.url);
  const cursor = searchParams.get('cursor');
  const limit = Math.min(Number(searchParams.get('limit')) || 20, 100);

  const items = await db.product.findMany({
    take: limit + 1,
    ...(cursor ? { cursor: { id: cursor }, skip: 1 } : {}),
    orderBy: { createdAt: 'desc' },
  });

  const hasMore = items.length > limit;
  const page = hasMore ? items.slice(0, limit) : items;

  return NextResponse.json({
    items: page.map((p) => ({ id: p.id, name: p.name, priceCents: p.priceCents })),
    nextCursor: hasMore ? page[page.length - 1].id : null,
  });
}

Consistent response shapes — items, nextCursor, and a stable sort key — let front-end code paginate without special cases for the first page versus later ones.

Idempotency and safe retries

Mobile clients retry requests when a connection drops, and users double-click submit buttons. A POST that creates a record without an idempotency key can create two records when the first response is lost. The standard fix is a client-generated key stored alongside the write: the first request with a given key performs the action and stores the result; a replay returns the stored response without side effects.

// app/api/orders/route.js — idempotent creation
import { NextResponse } from 'next/server';
import { db } from '@/lib/db';

export async function POST(request) {
  const key = request.headers.get('idempotency-key');
  if (!key) {
    return NextResponse.json(
      { error: 'Idempotency-Key header required' },
      { status: 400 }
    );
  }

  const existing = await db.idempotentRecord.findUnique({ where: { key } });
  if (existing) {
    return NextResponse.json(JSON.parse(existing.responseBody), {
      status: 200,
      headers: { 'Idempotent-Replay': 'true' },
    });
  }

  const body = await request.json();
  const order = await db.order.create({ data: body });
  const responseBody = JSON.stringify({ orderId: order.id, status: 'created' });

  await db.idempotentRecord.create({
    data: { key, responseBody, createdAt: new Date() },
  });

  return NextResponse.json(JSON.parse(responseBody), { status: 201 });
}

The header check that rejects requests without a key feels strict until the first lost-response duplicate order appears in a support queue. Payment providers made this pattern mandatory for a reason, and any endpoint that creates billable or scarce resources deserves the same treatment.

Production pitfalls

The recurring issues are unvalidated bodies trusted as typed input, missing 404 branches that let ORM "record not found" exceptions bubble up as 500s, and handlers that authenticate with a cookie check duplicated in eight files instead of one middleware or helper. Also watch the edge: route handlers that use Node-only libraries must not be forced onto the Edge runtime, or the build will fail with module resolution errors that look mysterious until you remember the runtime flag.

Common Mistakes

Exporting a catch-all handler that switches on request.method manually

Fix: Export GET, POST, PATCH, and DELETE by name; Next.js handles routing and returns 405 for missing verbs.

Returning 500 with the raw ORM error message

Fix: Log the error server-side, return a generic message with a correlation id, and map known failures to 404 or 409 explicitly.

Forgetting that params is async in newer Next.js versions

Fix: Await params before using it; treating it as a plain object yields undefined segment values.

Caching a per-user GET at the CDN by default

Fix: Set Cache-Control no-store on authenticated responses, or opt in to revalidation only for genuinely public data.

Best Practices

  • Validate every body and query with a schema library such as zod before touching the database
  • Centralize error mapping in one helper so every handler returns the same body shape
  • Keep route handlers thin: parse, authorize, call a lib function, shape the response
  • Version public APIs with a path prefix such as /api/v1 before partners depend on your shapes

Interview Questions

Q1: How does Next.js respond when you request a method that is not exported?

It returns 405 Method Not Allowed automatically, which discourages accidental acceptance of unsafe verbs.

Q2: When should a GET route handler be cached?

Only when it is public, deterministic, and free of dynamic APIs like cookies or headers. Anything per-user must be no-store or explicitly revalidated.

Q3: Route handler or Server Action — how do you decide?

If the caller is outside your React tree, use a route handler. If it is a form or event inside your app, a Server Action gives you progressive enhancement with less code.

Key Takeaways

  • Route handlers are Web-standard Request and Response functions exported by verb from route.js files.
  • Validate inputs with schemas and map failures to 400 or 422 with structured issues, not generic 500s.
  • Dynamic params arrive as a Promise in modern Next.js and must be awaited.
  • Streaming handlers return a ReadableStream and should set no-store unless the output is public.
  • Keep handlers thin and share authorization, logging, and error shaping through helpers.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Next.js Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement