Lab: A Localized Catalog with Shareable Filters and a Members Area
Assemble the whole skill in one working app: a [lang] segment chosen by Proxy from a cookie or the browser language, a catalog whose filters live in the URL, per-route metadata, and a members area that Proxy guards with a session cookie.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: scaffold the app
- Step 2: the [lang] segment and its dictionary
- Step 3: Proxy adds the locale and guards the members area
- Step 4: the catalog with shareable filters
- Step 5: the members area and the demo sign-in
- Step 6: what the build reports
- Troubleshooting
- Check your understanding
- Apply it: stretch tasks
- 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
- Create nested routes, shared layouts and dynamic segments with the App Router file conventions (page, layout, loading, error, not-found).
- Navigate with Link and the router, read route params and search params, and keep filter, sort and pagination state in the URL.
- Add per-route metadata for search and sharing, loading UI and error boundaries so every route fails and waits gracefully.
- 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. Goal and setup
By the end of this lab you will have one small app that exercises every convention from this skill: file-system routes under a [lang] segment, nested layouts, a dynamic detail route, filters and pagination that live entirely in the URL, per-route metadata, and a Proxy that adds the locale segment and keeps signed-out visitors out of the members area.
You need: Node.js 22 or later and npm. The lab was built and every output captured with Node 22.23 (v22.23.5 with npm 10.9.9 for the install, v22.23.2 for the build and server), Next.js 16.4.6 and React 19.3.0, the versions [email protected] writes into package.json. Node 26 is the active LTS line at the time of writing; Node 22 is in maintenance and still supported. Nothing is installed globally; the app carries its own dependencies. The finished tree looks like this:
catalog-lab/
├── proxy.ts locale negotiation and members guard
├── lib/
│ ├── products.ts product data (same as earlier lessons)
│ └── i18n.ts LANGS, dictionary, dictFor()
└── app/
├── session/route.ts POST handler: set the demo session cookie
└── [lang]/
├── layout.tsx root layout: <html lang>, nav, per-lang metadata
├── page.tsx /en, /fr
├── catalog/
│ ├── page.tsx filters, sorting and pagination from the URL
│ └── [slug]/
│ ├── page.tsx product detail + generateMetadata
│ └── not-found.tsx unknown slugs
├── members/page.tsx members area (session cookie required)
└── sign-in/page.tsx demo sign-in form02. Step 1: scaffold the app
$ npx [email protected] catalog-lab --ts --no-eslint --no-tailwind \
--no-src-dir --app --turbopack --import-alias "@/*" --use-npm --disable-gitUsing defaults for unprovided options:
--no-react-compiler No React Compiler
--cache-components Cache Components
--agents-md AGENTS.md
--no-agent-feedback No agent feedback
Creating a new Next.js app in …/catalog-lab.
Installing dependencies:
- next
- react
- react-dom
Generating route types...
✓ Types generated successfully
Success! Created catalog-lab at …/catalog-labTwo defaults matter. cacheComponents switches on the modern caching model: pages that read request data (search params, cookies) either stream behind a Suspense boundary or declare instant = false to be allowed to block, and the build reports each route's behaviour. Route types are generated for you, which is what makes the PageProps and LayoutProps helpers available. (The --agents-md default also writes an AGENTS.md that points coding assistants at the docs bundled in node_modules/next/dist/docs; this lab does not need it.) Next, delete the generated app/layout.tsx and app/page.tsx (keep app/globals.css): in this app app/[lang]/layout.tsx is the root layout that renders <html>, and Proxy gives every URL a language segment, so a top-level layout or page would nest a second <html> or answer / instead of the redirect. Then add lib/products.ts — the same five products in three categories that the earlier lessons used, with getProducts(category, sort) and getProduct(slug) helpers.
export const CATEGORIES = ['brewers', 'grinders', 'kettles'] as const;
export interface Product {
slug: string;
title: string;
category: (typeof CATEGORIES)[number];
priceGBP: number;
blurb: string;
}
export const PRODUCTS: Product[] = [
{
slug: 'french-press',
title: 'French press',
category: 'brewers',
priceGBP: 24,
blurb: 'Classic borosilicate glass immersion brewer.',
},
{
slug: 'stovetop-espresso',
title: 'Stovetop espresso maker',
category: 'brewers',
priceGBP: 32,
blurb: 'Eight-sided moka pot producing rich concentrated coffee.',
},
{
slug: 'workshop-grinder',
title: 'Workshop grinder',
category: 'grinders',
priceGBP: 129,
blurb: 'Precision electric flat-burr grinder with stepless adjustment.',
},
{
slug: 'hand-grinder',
title: 'Hand grinder',
category: 'grinders',
priceGBP: 45,
blurb: 'Dual-bearing conical steel burr hand grinder.',
},
{
slug: 'gooseneck-kettle',
title: 'Gooseneck kettle',
category: 'kettles',
priceGBP: 55,
blurb: 'A precision pour for filter coffee.',
},
];
export function getProducts(category?: string, sort = 'title'): Product[] {
const list = category
? PRODUCTS.filter((p) => p.category === category)
: [...PRODUCTS];
if (sort === 'price-asc') {
list.sort((a, b) => a.priceGBP - b.priceGBP);
} else if (sort === 'price-desc') {
list.sort((a, b) => b.priceGBP - a.priceGBP);
} else {
list.sort((a, b) => a.title.localeCompare(b.title));
}
return list;
}
export function getProduct(slug: string): Product | undefined {
return PRODUCTS.find((p) => p.slug === slug);
}03. Step 2: the [lang] segment and its dictionary
export const LANGS = ['en', 'fr'] as const;
export type Lang = (typeof LANGS)[number];
export 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'. */
// Entries are read in order; a production version would also sort by q-value.
export 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 interface Dictionary {
siteName: string;
mainNav: string;
catalog: string;
members: string;
sortBy: string;
apply: string;
products: string;
pages: string;
welcomeTitle: string;
welcomeBody: string;
exploreCatalog: string;
signInTitle: string;
emailLabel: string;
signInButton: string;
membersDenied: string;
membersTitle: string;
membersBody: string;
}
export const DICT: Record<Lang, Dictionary> = {
en: {
siteName: 'Copperleaf Supplies',
mainNav: 'Main navigation',
catalog: 'Catalog',
members: 'Members',
sortBy: 'Sort by',
apply: 'Apply',
products: 'Products',
pages: 'Pages',
welcomeTitle: 'Welcome to Copperleaf Supplies',
welcomeBody: 'Curated coffee brewing tools, delivered to your door.',
exploreCatalog: 'Explore the catalog',
signInTitle: 'Sign in',
emailLabel: 'Email address',
signInButton: 'Sign in',
membersDenied: 'Please sign in to access member benefits.',
membersTitle: 'Members Area',
membersBody: 'Exclusive equipment previews and subscriber benefits.',
},
fr: {
siteName: 'Copperleaf Supplies',
mainNav: 'Navigation principale',
catalog: 'Catalogue',
members: 'Membres',
sortBy: 'Trier par',
apply: 'Appliquer',
products: 'Produits',
pages: 'Pages',
welcomeTitle: 'Bienvenue chez Copperleaf Supplies',
welcomeBody: 'Outils de torréfaction et préparation de café artisanal.',
exploreCatalog: 'Explorer le catalogue',
signInTitle: 'Connexion',
emailLabel: 'Adresse e-mail',
signInButton: 'Se connecter',
membersDenied: 'Veuillez vous connecter pour accéder à l’espace membres.',
membersTitle: 'Espace membres',
membersBody: 'Prévisualisations exclusives et avantages abonnés.',
},
};
/** Params come in as strings; validate before using, and fall back to English. */
export function dictFor(value: string): Dictionary {
return isLang(value) ? DICT[value] : DICT.en;
}import type { Metadata } from 'next';
import Link from 'next/link';
import { dictFor, LANGS } from '../../lib/i18n';
import '../globals.css';
export function generateStaticParams() {
return LANGS.map((lang) => ({ lang }));
}
export async function generateMetadata(
props: LayoutProps<'/[lang]'>,
): Promise<Metadata> {
const { lang } = await props.params;
const dict = dictFor(lang);
return {
title: { default: dict.siteName, template: `%s · ${dict.siteName}` },
};
}
export default async function RootLayout({ children, params }: LayoutProps<'/[lang]'>) {
const { lang } = await params;
const dict = dictFor(lang);
return (
<html lang={lang}>
<body>
<header>
<nav aria-label={dict.mainNav}>
<Link href={`/${lang}`}>{dict.siteName}</Link>
<Link href={`/${lang}/catalog`}>{dict.catalog}</Link>
<Link href={`/${lang}/members`}>{dict.members}</Link>
</nav>
</header>
<main>{children}</main>
</body>
</html>
);
}import Link from 'next/link';
import { dictFor } from '../../lib/i18n';
export default async function HomePage(props: PageProps<'/[lang]'>) {
const { lang } = await props.params;
const dict = dictFor(lang);
return (
<section>
<h1>{dict.welcomeTitle}</h1>
<p>{dict.welcomeBody}</p>
<p>
<Link href={`/${lang}/catalog`}>{dict.exploreCatalog}</Link>
</p>
</section>
);
}This layout is the app's root layout: it renders <html> and <body>, and lang comes from the URL, so each locale serves a document whose lang attribute is actually correct — an accessibility win, since screen readers pick a voice from it. generateStaticParams lists the known languages so their shells prerender, and the metadata template is built per language. dictFor validates the parameter: the router types lang as string because a route can always be asked for an unknown value, and falling back to English beats indexing a dictionary with an unvalidated string.
04. Step 3: Proxy adds the locale and guards the members area
import { NextResponse, type NextRequest } from 'next/server';
import { isLang, negotiate } from './lib/i18n';
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 -H 'Cookie: lang=fr' http://localhost:3132/ | 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: /fr/
HTTP/1.1 307 Temporary Redirect
location: /fr/sign-inRun npm run build first, then npx next start -p 3132. Four requests, four decisions before any page renders. Plain curl sends no language header, so the visitor lands on English; a French browser setting negotiates to French; an explicit lang cookie beats the header because it records a choice the visitor made; and /fr/members without a session cookie is bounced to the sign-in page. The matcher keeps Proxy away from framework assets and the session route handler — without it, the sign-in page's own CSS and JavaScript would be redirected too.
05. Step 4: the catalog with shareable filters
import Link from 'next/link';
import { getProducts } from '../../../lib/products';
import { dictFor } from '../../../lib/i18n';
export const instant = false;
const PAGE_SIZE = 2;
const SORTS = ['title', 'price-asc', 'price-desc'] as const;
function first(value: string | string[] | undefined): string | undefined {
return Array.isArray(value) ? value[0] : value;
}
export default async function CatalogPage(props: PageProps<'/[lang]/catalog'>) {
const { lang } = await props.params;
const params = await props.searchParams;
const dict = dictFor(lang);
const category = first(params.category);
const sort = first(params.sort) ?? 'title';
const requested = Number.parseInt(first(params.page) ?? '1', 10);
const products = getProducts(category, sort);
const pageCount = Math.max(1, Math.ceil(products.length / PAGE_SIZE));
const page = Math.min(Math.max(1, requested || 1), pageCount);
const visible = products.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);
const pageHref = (n: number) => {
const next = new URLSearchParams();
if (category) next.set('category', category);
if (sort !== 'title') next.set('sort', sort);
if (n > 1) next.set('page', String(n));
const query = next.toString();
return query ? `/${lang}/catalog?${query}` : `/${lang}/catalog`;
}; return (
<>
<h1>{dict.catalog}</h1>
<form action={`/${lang}/catalog`} method="get">
<label htmlFor="sort">{dict.sortBy}</label>
<select id="sort" name="sort" defaultValue={sort}>
{SORTS.map((value) => (
<option key={value} value={value}>
{value}
</option>
))}
</select>
<button type="submit">{dict.apply}</button>
</form>
<h2>{dict.products}</h2>
<ul>
{visible.map((product) => (
<li key={product.slug}>
<Link href={`/${lang}/catalog/${product.slug}`}>
{product.title}, £{product.priceGBP}
</Link>
</li>
))}
</ul>
<nav aria-label={dict.pages}>
{pageCount > 1 &&
Array.from({ length: pageCount }, (_, index) => index + 1).map((n) => (
<Link key={n} href={pageHref(n)}
aria-current={n === page ? 'page' : undefined}>
{n}
</Link>
))}
</nav>
</>
);
}$ curl -s 'http://localhost:3132/fr/catalog?category=grinders&sort=price-desc' \
| grep -oE '<html lang="[a-z]*"|<a href="/fr/catalog/[a-z-]*">[A-Za-z ]*'<html lang="fr"
<a href="/fr/catalog/workshop-grinder">Workshop grinder
<a href="/fr/catalog/hand-grinder">Hand grinderEverything from the URL-state lesson is here, now localized. The page reads searchParams on the server, so the filtered view is plain HTML: curl proves the document is French (<html lang="fr">), sorted high to low, and filtered to grinders — and every such address survives a reload, a bookmark and a paste into a chat. The filter form is a GET form, so it works with JavaScript disabled; the form label and button text come from the dictionary, matching the interface language to the URL language (the sort options still show their raw values such as price-asc; translating them is a good extension). instant = false is there because of cacheComponents: a page that reads searchParams with no Suspense boundary above it fails the static-shell check that next build runs, and instant = false switches that check off so the route may block until its data is ready. It does not change how the page renders; the whole list is in the initial HTML because nothing here streams behind a fallback. Predict what npm run build prints if you delete that line, then try it (and put the line back).
import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import { getProduct, getProducts } from '../../../../lib/products';
export async function generateStaticParams() {
return getProducts().map((p) => ({ slug: p.slug }));
}
export async function generateMetadata(
props: PageProps<'/[lang]/catalog/[slug]'>,
): Promise<Metadata> {
const { slug } = await props.params;
const product = getProduct(slug);
if (!product) return { title: 'Product not found' };
return { title: product.title };
}
export default async function ProductDetailPage(
props: PageProps<'/[lang]/catalog/[slug]'>,
) {
const { slug } = await props.params;
const product = getProduct(slug);
if (!product) notFound();
return (
<article>
<h1>{product.title}</h1>
<p>£{product.priceGBP}</p>
<p>{product.blurb}</p>
</article>
);
}import Link from 'next/link';
export default function NotFound() {
return (
<section>
<h1>404 — Product Not Found</h1>
<p>This product does not exist in our catalog.</p>
<Link href="/en/catalog">Back to catalog</Link>
</section>
);
}06. Step 5: the members area and the demo sign-in
import { cookies } from 'next/headers';
import Link from 'next/link';
import { dictFor } from '../../../lib/i18n';
export const instant = false;
export default async function MembersPage(props: PageProps<'/[lang]/members'>) {
const { lang } = await props.params;
const dict = dictFor(lang);
const store = await cookies();
const session = store.get('session')?.value;
if (!session) {
// Proxy keeps most signed-out visitors out; this check is the real gate,
// because it runs next to the member data it protects.
return (
<section>
<p role="alert">{dict.membersDenied}</p>
<p>
<Link href={`/${lang}/sign-in`}>{dict.signInTitle}</Link>
</p>
</section>
);
}
return (
<section>
<h1>{dict.membersTitle}</h1>
<p>{dict.membersBody}</p>
</section>
);
}import { dictFor } from '../../../lib/i18n';
export default async function SignInPage(props: PageProps<'/[lang]/sign-in'>) {
const { lang } = await props.params;
const dict = dictFor(lang);
return (
<section>
<h1>{dict.signInTitle}</h1>
<form action="/session" method="post">
<input type="hidden" name="lang" value={lang} />
<label htmlFor="email">{dict.emailLabel}</label>
<input id="email" name="email" type="email" required />
<button type="submit">{dict.signInButton}</button>
</form>
</section>
);
}import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
// Demo sign-in: a plain HTML form posts here. In a real app this is where you
// would verify credentials and create a server session.
export async function POST(request: NextRequest) {
const form = await request.formData();
const lang = form.get('lang') === 'fr' ? 'fr' : 'en';
const response = NextResponse.redirect(
new URL(`/${lang}/members`, request.url),
303,
);
response.cookies.set('session', 'demo', {
httpOnly: true,
sameSite: 'lax',
path: '/',
});
return response;
}The sign-in page (app/[lang]/sign-in/page.tsx) is a plain form posting to /session, where a route handler answers POST requests: it sets the cookie and redirects with 303, so the browser follows with a GET. Two layers of protection surround the members data. Proxy performs the fast, optimistic check — no cookie, no page. The members page then re-checks the cookie next to the data it would show, because a Proxy redirect narrows paths but authorises nothing: requests can also arrive through server actions or handlers, and a cookie's presence proves nothing about what the visitor may do. In a real app the page's check would verify a server session and the data layer would filter by owner.
$ curl -s http://localhost:3132/fr/sign-in \
| grep -oE '<h1>[^<]*</h1>|<form[^>]*>|<label[^>]*>[^<]*</label>'
$ curl -si -X POST -d 'lang=fr&[email protected]' \
http://localhost:3132/session | grep -iE 'HTTP/|location|set-cookie'
$ curl -sI http://localhost:3132/fr/members | head -2
$ curl -s -H 'Cookie: session=demo' http://localhost:3132/fr/members \
| grep -oE '<h1>[^<]*</h1>'<h1>Connexion</h1>
<form action="/session" method="post">
<label for="email">Adresse e-mail</label>
HTTP/1.1 303 See Other
location: http://localhost:3132/fr/members
set-cookie: session=demo; Path=/; HttpOnly; SameSite=lax
HTTP/1.1 307 Temporary Redirect
location: /fr/sign-in
<h1>Espace membres</h1>Read the five results as one story. The French sign-in page renders from the URL language. Posting the form sets an HttpOnly cookie — JavaScript cannot read it, which is exactly what you want from a session token — and redirects to the French members area. Without that cookie the members URL returns a 307 to sign-in before any page runs; with it, the page renders and the server-side check passes.
07. Step 6: what the build reports
$ npm run build├ /[lang]/members
│ ├ ƒ /[lang]/members
│ ├ ƒ /en/members
│ └ ƒ /fr/members
├ /[lang]/sign-in
│ ├ ◐ /[lang]/sign-in
│ ├ ○ /en/sign-in
│ └ ○ /fr/sign-in
└ ƒ /session
ƒ Proxy (Middleware)
○ (Static) prerendered as static content
◐ (Partial Prerender) prerendered as static HTML with dynamic server-streamed content
ƒ (Dynamic) server-rendered on demandThe build table is a map of your routing decisions. Known product and sign-in pages are static. The members pages are dynamic because they read cookies. And the single line ƒ Proxy (Middleware) confirms the file was picked up — if it is missing, proxy.ts is not at the project root. Copy this table into your notes when a route behaves unexpectedly: the symbol tells you what the framework thinks you asked for.
08. Troubleshooting
09. Check your understanding
10. Apply it: stretch tasks
Each of these deepens one objective from the skill:
- Add
deto LANGS with a German dictionary, then check negotiation withcurl -H "Accept-Language: de-DE,de;q=0.9". Notice that only the dictionary and the constant list change. - Persist the visitor's choice: after a successful sign-in, also set a
langcookie in the session handler, and confirm that a French cookie now beats an English browser header. - Replace the demo cookie with a real session: verify credentials in the handler, store a random token server-side, and have the members page validate that token before showing data. Read /skills/web-app-security for why the Proxy check must stay optimistic and the data-layer check authoritative.
- Add
app/robots.tsandapp/sitemap.tslisting everyenandfrURL fromgetProducts(), and check the emitted files withcurl.
For the rendering-model picture behind routes like these, continue with /skills/react-server-rendering.
11. Review prompt
Without looking back: which file decides the locale for /catalog, what does it read first, and what does it return? Where does <html lang> get its value, and why does that matter for screen readers? Which three places in this app touch the session cookie, and what is each one's job? And what does the ƒ symbol next to a route in the build output tell you?
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.