Route Handlers and proxy (middleware)
Pages return HTML for the browser, but a mobile app or a webhook needs a fixed URL that returns JSON. Route Handlers (route.ts) give you that, and proxy.ts (the Next.js 16 name for middleware) runs before every matching request for redirects, rewrites and headers.
66.1 Problem: HTML instead of JSON
- The mobile app team calls /api/products with fetch and parses JSON.
- The console shows 404 and then a SyntaxError: the Next.js HTML not-found page came back instead of JSON.
JavaScript
// mobile app codeconst res = await fetch( "http://localhost:3000/api/products");console.log(res.status);const data = await res.json();Output
> 404SyntaxError: Unexpected token '<',"<!DOCTYPE "... is not valid JSON66.2 Why is it used?
- So far the app folder only has pages, which return HTML; no /api/products route exists.
- Server Actions do not help: they are for your own React forms and have no fixed public URL.
- You need a URL that takes an HTTP request and returns a JSON response: a Route Handler.
66.3 GET in route.ts
- Create app/api/products/route.ts (a route file instead of a page).
- Export functions named after HTTP methods; GET handles every GET request to this URL.
- Response.json() converts the data to JSON and sends it.
TypeScript
// app/api/products/route.tsimport { products } from "@/lib/products"; export async function GET() { return Response.json(products);}Output
$ curl localhost:3000/api/products[{"id":1,"name":"Laptop","price":55000},{"id":2,"name":"Phone","price":20000},{"id":3,"name":"Headphones","price":2000}]66.4 NextRequest: query params
- For search the app sends ?q=lap; GET receives a NextRequest.
- req.nextUrl.searchParams.get("q") reads it; no q returns the whole list, otherwise filter by name.
TypeScript
import type { NextRequest } from "next/server";import { products } from "@/lib/products"; export async function GET(req: NextRequest) { const q = req.nextUrl.searchParams.get("q"); if (!q) return Response.json(products); const term = q.toLowerCase(); const list = products.filter((p) => p.name.toLowerCase().includes(term) ); return Response.json(list);}Output
$ curl "localhost:3000/api/products?q=lap"[{"id":1,"name":"Laptop","price":55000}]66.5 Dynamic route: [id]
- Create app/api/products/[id]/route.ts, a dynamic segment just like pages.
- The second argument is a context; await ctx.params to get the id.
- Not found -> error JSON with status 404; otherwise the product.
TypeScript
// app/api/products/[id]/route.tsimport { products } from "@/lib/products"; export async function GET( _req: Request, ctx: RouteContext<"/api/products/[id]">) { const id = Number((await ctx.params).id); const item = products.find((p) => p.id === id); if (!item) { const error = "Product not found"; return Response.json({ error }, { status: 404 }); } return Response.json(item);}Output
$ curl localhost:3000/api/products/2{"id":2,"name":"Phone","price":20000} $ curl -i localhost:3000/api/products/9HTTP/1.1 404 Not Found{"error":"Product not found"}66.6 POST: a new product
- Export POST from the same route.ts; read the body with await req.json().
- Missing name or price -> 400; otherwise add the product and return it with 201.
TypeScript
// app/api/products/route.ts (same file as GET)export async function POST(req: Request) { const body = await req.json(); if (!body.name || !body.price) { return Response.json( { error: "name and price required" }, { status: 400 } ); } const id = products.length + 1; const item = { id, ...body }; products.push(item); return Response.json(item, { status: 201 });}Output
$ curl -i -X POST -d @mouse.json \ localhost:3000/api/productsHTTP/1.1 201 Created{"id":4,"name":"Mouse","price":500}| Status | Meaning | Where used here |
|---|---|---|
| 200 OK | Success | GET list / single product |
| 201 Created | New resource created | POST new product |
| 400 Bad Request | Invalid input | POST without name or price |
| 404 Not Found | Resource missing | GET /api/products/9 |
| 307 Temporary Redirect | Go to another URL | proxy sends to /login |
66.7 The request flow
- Step 1
1.Request: browser, mobile app or webhook
- Step 2
2.proxy.ts: redirect, rewrite or next()
- Step 3
3.Next.js matches the URL
- Step 4
4.page.tsx renders HTML or route.ts returns JSON
- Step 5
5.Response goes back to the client
66.8 proxy.ts: login check
- proxy.ts (called middleware before Next.js 16) lives in the project root next to the app folder.
- The proxy function reads the session cookie; no cookie -> NextResponse.redirect to /login.
- Cookie present -> NextResponse.next() lets the request continue.
- config.matcher limits it to /dashboard paths.
TypeScript
// proxy.ts (project root, next to app/)import { NextResponse } from "next/server";import type { NextRequest } from "next/server"; export function proxy(req: NextRequest) { const session = req.cookies.get("session"); if (!session) { const login = new URL("/login", req.url); return NextResponse.redirect(login); } return NextResponse.next();} export const config = { matcher: ["/dashboard/:path*"],};Output
$ curl -i localhost:3000/dashboardHTTP/1.1 307 Temporary Redirectlocation: /login $ curl -i -b session=abc localhost:3000/dashboardHTTP/1.1 200 OK66.9 Checkpoint: page.tsx and route.ts in the same folder
- Build error: one URL can be owned by only one file, a page (HTML) or a route handler (data).
- That is why API routes usually live in a separate api folder.
Output
app/ shop/ page.tsx route.tsOutput
$ npm run buildError: Turbopack build failed with 1 error:Conflicting route and page at /shop:route at /shop/route and page at /shop/page66.10 Common mistakes
- Fetching your own route handler from a Server Component via localhost: an unnecessary network round trip, and it can fail at build when no server is running.
- Fix: import the data function and call it directly; keep route handlers for outside clients.
- Myth: a login check in the proxy secures the whole app. In 2025 middleware had a bypass bug via a special header.
- Use the proxy only for fast redirects, and do the real auth check close to the data: in the page, Server Action and route handler.
React (TSX)
// Wrong: extra HTTP call to your own serverexport default async function ShopPage() { const res = await fetch( "http://localhost:3000/api/products" ); const products = await res.json(); return <h1>{products.length} products</h1>;}React (TSX)
// Right: direct function call, no networkimport { getProducts } from "@/lib/products"; export default async function ShopPage() { const products = await getProducts(); return <h1>{products.length} products</h1>;}66.11 Comparison: Server Action vs Route Handler vs proxy
| Need | Use | Why |
|---|---|---|
| A form or button in your own UI changes data | Server Action | Next.js handles URL, fetch and JSON for you |
| Mobile app or webhook calls you | Route Handler | Fixed public URL + JSON |
| Public JSON API, custom headers | Route Handler | Full control of Request/Response |
| Work before every request | proxy.ts | Redirects, rewrites, setting headers |
66.12 Interview tips
- A Route Handler is a route.ts file in the app folder that exports functions named after HTTP methods (GET, POST...).
- It uses the Web standard Request and Response APIs; NextRequest adds helpers like cookies and nextUrl.searchParams.
- In Next.js 16 proxy is the new name for middleware; it runs on the Node runtime before the request.
- Auth is checked not only in the proxy but also close to the data.
- A page and a route cannot share the same URL segment.