Skip to content
Visual explainer 3h to learn 3 steps

Route handlers & middleware

Build JSON endpoints and protect routes with middleware.

By Invicly Tech, , in Frontend with React & Next.js. About 10 minutes to read.

Topic 24 of 36

In short

Route handlers are route.ts files that export functions like GET and POST to build HTTP endpoints. Middleware runs before matching routes and can redirect or block requests, for example when a user is not signed in.

Explained simply

Sometimes your app needs a real web address that other programs can call: a mobile app loading data, a payment provider sending a webhook, or a script uploading files. In Next.js you build these with route handlers.

A route handler is a file called route.ts inside the app folder. You export functions named after HTTP methods, like GET or POST. Each one receives the request and returns a response, usually JSON.

Good APIs use status codes to tell the caller what happened: 200 for OK, 201 for created, 400 for bad input, 401 when not signed in, 404 when not found, 500 for a server error. Callers rely on these numbers, so do not return 200 for errors.

A proxy file (called middleware before Next.js 16) runs before your routes. It can check for a login cookie and redirect visitors to the sign-in page. It is a fast first filter, not the only lock: the route itself must still check permissions.

Press Play on a diagram to walk through it one step at a time.

SequenceA request through middleware to a handler
Client
Middleware
Route handler
  1. 1GET /api/notes with cookie
    Client to Middleware: GET /api/notes with cookie
  2. 2Check session cookie
    Middleware to Middleware: Check session cookie
  3. 3Redirect to /login if missing
    Middleware to Client: Redirect to /login if missing
  4. 4Otherwise continue
    Middleware to Route handler: Otherwise continue
  5. 5200 JSON response
    Route handler to Client: 200 JSON response
SequencePATCH /api/notes/7 by a user who does not own note 7
Client
Proxy
Route handler
Database
  1. 1PATCH with session cookie
    Client to Proxy: PATCH with session cookie
  2. 2cookie present: next()
    Proxy to Route handler: cookie present: next()
  3. 3verify session: user 12
    Route handler to Route handler: verify session: user 12
  4. 4find note 7 where userId = 12
    Route handler to Database: find note 7 where userId = 12
  5. 5no row
    Database to Route handler: no row
  6. 6404 Not Found (do not reveal it exists)
    Route handler to Client: 404 Not Found (do not reveal it exists)

In depth

Route handler basics

Put route.ts in any folder under app, such as app/api/notes/route.ts for /api/notes. Export GET, POST, PUT, PATCH, DELETE, HEAD or OPTIONS. Each receives a standard Web Request, or a NextRequest which adds helpers like request.nextUrl.searchParams and request.cookies. Dynamic segments work like pages: app/api/notes/[id]/route.ts receives a second argument { params }, which is a promise in current Next.js.

A folder cannot have both route.ts and page.tsx, because both would answer the same URL. Since Next.js 15, GET handlers are not cached by default. Return responses with Response.json(data, { status }) or NextResponse.json. For non-JSON, build a new Response with a body and headers, for example a CSV file with a Content-Type of text/csv.

  • app/api/notes/route.ts serves /api/notes
  • Second argument: { params } as a Promise
  • request.nextUrl.searchParams.get("q") for query strings
  • route.ts and page.tsx cannot share a folder

Status codes and error shapes

Pick status codes that match what happened, so clients can react without parsing messages. 200 OK for reads, 201 Created for a new resource (often with its data or a Location header), 204 No Content for a delete with no body. Client mistakes: 400 for invalid input, 401 when not authenticated, 403 when authenticated but not allowed, 404 when the item does not exist, 409 for a conflict like a duplicate email, 422 is also common for validation errors. Server failures: 500.

Keep one error shape for the whole API, such as { error: { code, message, fields } }, so clients write one error handler. Never send stack traces or database messages to the client; log them on the server. Wrap the handler body in try/catch and turn unexpected errors into a generic 500.

MapCommon status codes for a JSON API
Response status
  • 2xx success
    • 200 OK
    • 201 Created
    • 204 No Content
  • 4xx client problem
    • 400 Bad Request
    • 401 Unauthorized
    • 403 Forbidden
    • 404 Not Found
    • 409 Conflict
  • 5xx server problem
    • 500 Internal Server Error
    • 503 Service Unavailable

Proxy (formerly middleware)

Next.js 16 renamed middleware.ts to proxy.ts, and the exported function from middleware to proxy; the old name still works for now but is deprecated. The file sits at the project root (or in src). It runs before routes and before cached content are served, for every request that matches its config.matcher.

Inside, you can read cookies and headers, then return NextResponse.next() to continue, NextResponse.redirect(url) to send the user elsewhere, NextResponse.rewrite(url) to serve another path invisibly, or a Response directly. Use the matcher to skip static files and images, because the proxy runs on every matching request and adds latency. Keep it light: check that a session cookie exists, add headers, handle locales or redirects. Do not run slow database queries there.

FlowWhere proxy sits in a request
  1. 1
    Request arrives

    GET /dashboard with cookies

  2. 2
    Matcher

    Does this path match config.matcher?

  3. 3
    proxy()

    Light checks: cookie, locale, headers

  4. 4
    Decision

    next(), redirect() or rewrite()

  5. 5
    Route

    Page or route handler checks auth again

Why the proxy is not your only lock

Treat the proxy as an optimistic check. It sees only the request, and a typo in the matcher can leave a route unprotected. In March 2025, a vulnerability (CVE-2025-29927) let attackers skip Next.js middleware entirely with a special header on self-hosted apps; apps that also checked auth in their pages and handlers stayed safe.

The pattern recommended by the Next.js docs is a data access layer: a few server-only functions that verify the session and the user's rights right before reading or writing data. Every route handler, server action and server component calls them. Then the proxy only improves user experience, sending signed-out users to /login early, while security lives next to the data.

Learn it in 3 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Create a GET and POST route handler~1h
  2. 2
    Return JSON with proper status codes~1h
  3. 3
    Write middleware to protect routes~1h

Key points

  • Export GET, POST, PUT or DELETE from app/api/.../route.ts.
  • Return Response.json(data, { status }) with the correct HTTP status code.
  • Middleware should stay fast and do light checks; verify auth again near the data.
  • Next.js 16 renamed middleware.ts to proxy.ts; older versions use middleware.ts.

Key terms

Tap a card to flip it. 0/5 known

Examples

ts
// app/api/notes/route.ts
export async function GET() {
  const notes = await db.note.findMany();
  return Response.json(notes);
}

export async function POST(req: Request) {
  const body = await req.json();
  if (typeof body.text !== 'string' || !body.text) {
    return Response.json({ error: 'text is required' }, { status: 400 });
  }
  const note = await db.note.create({ data: { text: body.text } });
  return Response.json(note, { status: 201 });
}

GET and POST handlers with proper status codes.

A validated CRUD endpoint for one item

Step 1: read the id from the awaited params. Step 2: verify the session and return 401 if missing. Step 3: validate the JSON body with Zod and return 400 with field errors if invalid. Step 4: update only a note owned by this user; if none matched, return 404. Step 5: return the updated note with 200. DELETE would follow the same pattern and return 204.

ts
// app/api/notes/[id]/route.ts
import { z } from "zod";
import { getSession } from "@/lib/auth";
import { db } from "@/lib/db";

const Patch = z.object({ text: z.string().min(1).max(5000) });

export async function PATCH(req: Request, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const session = await getSession();
  if (!session) return Response.json({ error: "Sign in first" }, { status: 401 });
  const parsed = Patch.safeParse(await req.json().catch(() => null));
  if (!parsed.success) return Response.json({ error: z.flattenError(parsed.error).fieldErrors }, { status: 400 });
  const { count } = await db.note.updateMany({ where: { id, userId: session.user.id }, data: parsed.data });
  if (count === 0) return Response.json({ error: "Not found" }, { status: 404 });
  return Response.json({ id, ...parsed.data });
}

A proxy that sends signed-out users to login

Step 1: create proxy.ts at the project root (middleware.ts with a middleware function on Next.js 15). Step 2: read the session cookie. Step 3: if it is missing, redirect to /login and remember where the user wanted to go. Step 4: limit the matcher to the private areas so public pages and static files skip the proxy. Pages under /dashboard still verify the session properly.

ts
// proxy.ts
import { NextResponse, type NextRequest } from "next/server";

export function proxy(request: NextRequest) {
  const hasSession = request.cookies.has("session");
  if (!hasSession) {
    const url = new URL("/login", request.url);
    url.searchParams.set("next", request.nextUrl.pathname);
    return NextResponse.redirect(url);
  }
  return NextResponse.next();
}

export const config = {
  matcher: ["/dashboard/:path*", "/settings/:path*"],
};

Quick reference

  • app/api/x/route.ts exports GET, POST, PUT, PATCH or DELETE
  • Response.json(data, { status: 201 }) for created resources
  • 400 bad input, 401 not signed in, 403 not allowed, 404 missing, 409 conflict
  • Dynamic route handlers: { params }: { params: Promise<{ id: string }> }
  • Next.js 16: proxy.ts exporting proxy(); Next.js 15 and earlier: middleware.ts
  • Use config.matcher so the proxy skips static files and public pages
  • The proxy is a fast pre-check; verify auth again next to the data
  • Never return stack traces or raw database errors to clients

Common mistakes

  • Returning 200 for every response, including errors.
  • Relying only on middleware for authorization and skipping checks in handlers.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A signed-in user asks to delete a note that belongs to someone else. Which status is a good answer?

Question 2

2What does NextResponse.rewrite(url) do in the proxy?

Question 3

3Why should the proxy matcher exclude static files and images?

Question 4

4Can app/settings/ contain both page.tsx and route.ts?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write GET /api/health that returns { ok: true, time } with status 200 and a Cache-Control header of no-store.

  2. Exercise 2medium

    Write GET /api/search?q=... that returns 400 if q is missing or shorter than 2 characters, otherwise returns matching product names from a local array.

  3. Exercise 3hard

    Write a webhook handler POST /api/webhooks/payments that reads the raw body, verifies an HMAC-SHA256 signature from the x-signature header with a secret from env, and returns 401 for bad signatures.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is middleware deprecated in Next.js 16?
The file was renamed: Next.js 16 uses proxy.ts with an exported proxy function, and middleware.ts is deprecated. The features are the same.
Do I need route handlers if I use server actions?
For your own forms, often not. You still need route handlers for webhooks, mobile apps, public APIs and file downloads.
Where do I put API routes in the App Router?
Anywhere under app as a route.ts file; app/api/... is a common convention, not a requirement.

Go deeper

ShareXLinkedInWhatsApp