Where Routing Happens: Client Routers, File-System Routes and Proxy
Compare a client route table with file-system routes in a meta-framework, and meet Proxy: code that runs before a route renders to redirect, rewrite or guard requests.
Contentsand lesson path
On this page
- Why it matters
- Two places a URL can become UI
- What the server sees
- Proxy: logic before the route
- Check your understanding
- Apply it
- Review prompt
Lessons of Next.js App Router & Routing
- Where Routing Happens: Client Routers, File-System Routes and Proxy Concept · 25 min
- Pages, Layouts and Dynamic Segments Worked example · 25 min
- Navigation and Keeping State in the URL Worked example · 20 min
- Loading, Error and Metadata per Route Concept · 20 min
- Lab: A Localized Catalog with Shareable Filters and a Members Area Lab · 30 min
- Check: Draw the Route Map Knowledge check · 10 questions
What you will learn
- Compare file-system routing in a meta-framework with client-side routing in a single-page app (for example React Router) and explain when each fits.
- Run logic before a route renders with Proxy (formerly middleware): match paths, redirect or rewrite, and read or set cookies and headers, for example to choose a locale segment or send signed-out visitors to sign-in, while leaving real authorization checks to server code.
Prerequisites: React Components & State
01. Why it matters
The same URL can become a page in two very different places: inside the browser, after some JavaScript has matched it against a route table, or on the server, before any HTML is sent. Both approaches produce working apps, and many teams run both. Choosing between them, and understanding what each does on a plain reload, is the difference between a link that survives being pasted into a chat and one that shows a 404.
This lesson compares the two models with a running example, then introduces the third player in Next.js 16: Proxy (renamed from Middleware in Next.js 16), a function that runs before a route renders and can redirect, rewrite or guard a request. Every later lesson in this skill builds on these three ideas.
02. Two places a URL can become UI
In a single-page app built with a client-side router such as React Router, the mapping from URL to component lives in code that the browser downloads. You write a route table, the router watches the address bar, and when the URL changes it picks a component and renders it in place. Nothing needs to be requested from a server: the app was already loaded.
// A client-side route table: the browser matches the URL after the bundle loads.
const routes = [
{ path: "/", element: <Home /> },
{ path: "/catalog", element: <Catalog /> },
{ path: "/catalog/:slug", element: <Product /> },
];In the Next.js App Router, the mapping lives in the folder structure. Each folder under app is a URL segment, and a page file inside a folder is what makes that segment routable. The framework reads this structure at build time, which is what lets it split code per route and decide, route by route, whether to render on the server at request time, at build time, or stream parts of a page while the rest loads. You write folders and components; you never write the route table yourself.
app/
├── page.tsx # /
└── catalog/
├── page.tsx # /catalog
└── [slug]/
└── page.tsx # /catalog/gooseneck-kettle and any other slugBoth routers can navigate without a full page reload, read parameters such as a product slug, and nest layouts. A client router does all of this in the browser, using the History API: history.pushState swaps the URL without a page load, and back and forward buttons fire events the router listens to. The App Router does the same in the browser and prepares each route on the server first. What that means in practice is the subject of the next section. If you want a refresher on how the browser turns a response into pixels first, see /learn/browser-rendering-url-to-pixels-pipeline.
03. What the server sees
On a first visit, a reload or a link someone shared, the URL does not reach your JavaScript first. It goes to a server, and the server answers with whatever it has. In a static-hosted SPA it has one HTML file, usually index.html, and no idea that /orders/42 means anything. Unless the host is configured to serve index.html for unknown paths, the user gets a 404.
You can watch this with two tiny servers. The first is a minimal static file host with one page, like a CDN bucket in front of an SPA. The second is the Next.js app we build across this skill, which knows how to render /catalog/gooseneck-kettle on demand.
// A minimal static file host, like a CDN bucket: it serves files it has, 404 otherwise.
const http = require("node:http");
const pages = { "/": "<h1>Orders</h1><p>An SPA served as static files.</p>" };
http
.createServer((req, res) => {
const file = pages[req.url.split("?")[0]];
if (file) {
res.writeHead(200, { "content-type": "text/html" });
res.end(file);
} else {
res.writeHead(404, { "content-type": "text/html" });
res.end("<h1>404 Not Found</h1>");
}
})
.listen(3135, () => console.log("static host on http://localhost:3135"));$ node static-host.js
$ curl -sI http://localhost:3135/orders/42 | head -1
$ curl -sI http://localhost:3131/catalog/gooseneck-kettle | head -1static host on http://localhost:3135
HTTP/1.1 404 Not Found
HTTP/1.1 200 OKThe SPA route worked perfectly when the user clicked inside the app, and broke the moment the URL reached the server alone. The Next.js route answers 200 because the framework rendered HTML for that exact path. This is the practical gap between the two models: client routing needs a host rewrite to survive reloads and shared links, while a meta-framework produces real responses per route. Rewrites can be added (every host has a recipe), so SPAs are not broken — but you are configuring infrastructure to compensate for a routing table the server cannot see.
04. Proxy: logic before the route
Some routing decisions should not live in any page: send visitors without a session cookie to the sign-in page, pick a language from the browser settings, or rewrite an old URL to a new one. Next.js runs a special file for this called Proxy. You create proxy.ts at the project root (or inside src/), and it exports a function that receives the incoming request and returns a response: NextResponse.next() to carry on, NextResponse.redirect(url) to send the browser elsewhere, or NextResponse.rewrite(url) to serve a different route while the address bar stays put.
Proxy runs for every matched request before rendering, so it suits fast, optimistic checks. It is the wrong place for slow work or for real authorisation: a cookie being present proves nothing, and your data is also reachable through server actions and route handlers. Proxy narrows the path; the page and the data layer still verify everything. In the lab at the end of this skill you will build exactly that split.
Here is the Proxy file from that lab: it adds a language segment to every URL and keeps signed-out visitors out of the members area.
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
const LANGS = ['en', 'fr'] as const;
type Lang = (typeof LANGS)[number];
function isLang(value: string | undefined): value is Lang {
return (LANGS as readonly string[]).includes(value ?? '');
}
/** First supported language in an Accept-Language header, or 'en'. */
function negotiate(header: string | null): Lang {
for (const part of header?.split(',') ?? []) {
const code = part.split(';')[0]?.trim().slice(0, 2).toLowerCase();
if (isLang(code)) return code;
}
return 'en';
}export function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;
const first = pathname.split('/')[1];
// Every URL needs a locale segment; add one from the lang cookie, or from
// the Accept-Language header when the visitor has not chosen a language yet.
if (!isLang(first)) {
const stored = request.cookies.get('lang')?.value;
const lang = isLang(stored)
? stored
: negotiate(request.headers.get('accept-language'));
return NextResponse.redirect(new URL(`/${lang}${pathname}`, request.url));
}
// Optimistic check: a request without a session cookie goes to sign-in. The
// page itself still re-checks the cookie before it shows member data.
if (pathname.endsWith('/members') && !request.cookies.get('session')) {
return NextResponse.redirect(new URL(`/${first}/sign-in`, request.url));
}
return NextResponse.next();
}
export const config = {
matcher: ['/((?!_next/static|_next/image|favicon.ico|session).*)'],
};$ curl -sI http://localhost:3132/ | head -2
$ curl -sI -H 'Accept-Language: fr-CH, fr;q=0.9, en;q=0.8' \
http://localhost:3132/ | head -2
$ curl -sI http://localhost:3132/catalog | head -2
$ curl -sI http://localhost:3132/fr/members | head -2HTTP/1.1 307 Temporary Redirect
location: /en/
HTTP/1.1 307 Temporary Redirect
location: /fr/
HTTP/1.1 307 Temporary Redirect
location: /en/catalog
HTTP/1.1 307 Temporary Redirect
location: /fr/sign-inFour requests, four decisions, none of them inside a page. Plain curl sends no Accept-Language header, so the visitor gets English. A French browser setting is negotiated to French. /catalog is missing its locale segment, so it is redirected to /en/catalog rather than 404-ing. And /fr/members without a session cookie never renders at all — the response is a redirect to /fr/sign-in.
Two details in that file matter more than they look. The config.matcher narrows Proxy to page-like paths and excludes framework assets, because without a matcher Proxy runs on every request, including the CSS, JavaScript and images the sign-in page itself needs — a classic redirect loop. And matcher values must be constants so the build can analyse them. Second, negotiate reads only the header; the lang cookie, set when the visitor picks a language, wins over it, because an explicit choice should beat a browser default. Proxy is also not the only way to redirect: simple, fixed redirects belong in next.config.ts, and Proxy earns its keep when the decision depends on the request.
05. Check your understanding
06. Apply it
Pick an app you have built or know well, and answer in writing:
- For each of its URLs, does the server answer with real HTML for that path, or does everything fall back to one file that routes in the browser?
- If it is a SPA, find the rewrite rule that makes deep links work, or write the one-line Proxy-free version in
next.config.tsredirects for a fixed old path. - List two decisions that would suit Proxy (fast, per-request, no secrets) and one that must stay in the page or data layer (anything a cookie alone cannot prove).
Then skim the skill pages for /skills/react-components and /skills/react-server-rendering and note where the rendering boundary sits in each model.
07. Review prompt
Without looking back: where does a client-side router keep its URL-to-component mapping, and what does a reload of a deep link return from a plain static host? What three things can a Proxy function return, and what does each do to the address bar? Why does the matcher exist, and why should real permission checks still live next to the data?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.