Next.js i18n: Locale Routing, Middleware Negotiation, and Dictionaries
A [lang] segment gives every page a static, cacheable URL per language and middleware negotiates once. Where static rendering silently becomes dynamic, and how hreflang stays honest.

Quick Summary
Internationalisation in the App Router is routing, not a library problem. A locale segment [lang] at the top of app/ gives every page a static, cacheable URL per language; middleware negotiates the locale for requests that arrive without one; dictionaries are JSON imported per request so a build only ships the strings a page needs.
The three decisions are: how the locale appears in the URL (sub-path, sub-domain, or cookie), where negotiation happens (middleware versus a route), and whether pages are statically generated per locale. Static generation is the payoff — generateStaticParams returning locales plus content slugs produces en/blog/hello and ko/blog/hello as two prerendered files with correct hreflang.
The trap is that next-intl, react-i18next, and hand-rolled getDictionary all look interchangeable in examples but differ on one thing that decides your architecture: whether the locale is a route parameter (static) or request state read from cookies and headers (dynamic).
Basic Syntax & Core Signatures
// app/[lang]/layout.tsx
import { notFound } from "next/navigation";
import { getDictionary, type Locale } from "@/lib/dictionaries";
export async function generateStaticParams() {
return [{ lang: "en" }, { lang: "ko" }, { lang: "ja" }];
}
export default async function LangLayout({
children,
params,
}: {
children: React.ReactNode;
params: Promise<{ lang: Locale }>;
}) {
const { lang } = await params;
const dict = await getDictionary(lang); // validated inside
return (
<html lang={lang}>
<body>{children}</body>
</html>
);
}// lib/dictionaries.ts — explicit imports keep bundles per-locale
export const locales = ["en", "ko", "ja"] as const;
export type Locale = (typeof locales)[number];
const dictionaries = {
en: () => import("./dictionaries/en.json").then((m) => m.default),
ko: () => import("./dictionaries/ko.json").then((m) => m.default),
ja: () => import("./dictionaries/ja.json").then((m) => m.default),
};
export const hasLocale = (v: string): v is Locale => locales.includes(v as Locale);
export async function getDictionary(locale: Locale) {
if (!hasLocale(locale)) throw new Error(`Unsupported locale: ${locale}`);
return dictionaries[locale]();
}Middleware does the negotiation once, so pages never have to guess:
// middleware.ts (Next.js 16: proxy.ts)
import { NextRequest, NextResponse } from "next/server";
import { locales } from "@/lib/dictionaries";
export function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;
if (locales.some((l) => pathname === `/${l}` || pathname.startsWith(`/${l}/`))) {
return NextResponse.next();
}
const cookieLang = req.cookies.get("lang")?.value;
const headerLang = req.headers.get("accept-language")?.split(",")[0]?.split("-")[0];
const lang = cookieLang && locales.includes(cookieLang) ? cookieLang
: headerLang && locales.includes(headerLang) ? headerLang
: "en";
const url = req.nextUrl.clone();
url.pathname = `/${lang}${pathname === "/" ? "" : pathname}`;
return NextResponse.redirect(url);
}
export const config = { matcher: ["/((?!api|_next|.*\\..*).*)"] };The matcher must exclude _next, api, and anything with a file extension; otherwise the redirect applies to CSS, images, and your own API routes, which produces redirect loops and broken assets.
Key Comparison Table
| Strategy | URL shape | SEO | Static per locale | Cost |
|---|---|---|---|---|
Sub-path /[lang]/... | example.com/ko/blog | Strong, simple | Yes | Lowest; one deployment |
Sub-domain ko.example.com | ko.example.com/blog | Strong, separate hosts | Yes | DNS plus per-host build or rewrite |
| Cookie or header only | example.com/blog | Weak — one URL, many languages | No, dynamic | Simplest URLs, worst caching |
| Domain per market | example.kr | Strong, strongest signals | Yes | Highest; separate properties |
| Client-only switch | example.com/blog | Poor, no per-locale URL | No | Cheapest, not indexable per locale |
| Library | Locale source | Static rendering | Formatting (dates, plurals) |
|---|---|---|---|
| Hand-rolled dictionaries | Route param | Yes | Manual, Intl |
next-intl | Route param or request | Yes, with setRequestLocale | ICU messages built in |
react-i18next | Provider in client tree | Limited; mostly client | i18next formatters |
Practical Edge Cases & Deep Dives
1. Static generation with a library that reads request state
next-intl server functions default to reading the locale from the request, which silently makes the page dynamic. Calling setRequestLocale(lang) at the top of the layout and each page restores static rendering, and it must be called in every segment that reads translations, not just the layout:
// app/[lang]/page.tsx
import { setRequestLocale, getTranslations } from "next-intl/server";
export default async function Home({ params }: { params: Promise<{ lang: string }> }) {
const { lang } = await params;
setRequestLocale(lang);
const t = await getTranslations("home");
return <h1>{t("title")}</h1>;
}The symptom to look for is ƒ (Dynamic) next to the route in next build output. If a locale page shows that, one segment is still reading headers, and the fix is one line in that segment — not a rewrite of the layout.
2. hreflang, canonical, and the default locale
Each locale page needs its own canonical plus alternates that point at sibling locales. Getting the default locale wrong — for example canonicalising en pages to the unprefixed /blog that middleware then redirects — splits ranking signals across two URLs.
export async function generateMetadata({ params }: { params: Promise<{ lang: string }> }) {
const { lang } = await params;
return {
alternates: {
canonical: `https://example.com/${lang}/blog`,
languages: {
en: "https://example.com/en/blog",
ko: "https://example.com/ko/blog",
"x-default": "https://example.com/en/blog",
},
},
};
}Use absolute URLs in languages; relative paths are ignored by several crawlers. x-default should match the locale middleware would pick for an unknown visitor.
3. Negotiation order and the Accept-Language quality factor
accept-language: fr-CH, fr;q=0.9, en;q=0.8 means French first, English as a fallback. Taking split(",")[0] is fine for simple cases but ignores q=0, which a client uses to mean "do not send me this". Respect q=0 or the user gets a language they explicitly refused:
function negotiate(header: string | null, supported: readonly string[]) {
if (!header) return null;
const ranked = header.split(",").map((part) => {
const [tag, ...attrs] = part.trim().split(";");
const q = attrs.find((a) => a.trim().startsWith("q="));
return { tag: tag.split("-")[0].toLowerCase(), q: q ? Number(q.split("=")[1]) : 1 };
}).filter((x) => x.q > 0).sort((a, b) => b.q - a.q);
return ranked.map((r) => r.tag).find((t) => supported.includes(t)) ?? null;
}Also keep the order cookie → header → default. Reversing it means a user who explicitly picked Korean gets English on every visit, because their browser says en-US.
4. Persisting the choice without a redirect loop
When the user switches language, write the cookie and redirect to the sibling path. Doing it in a Server Action avoids a client round trip and keeps cookies().set legal:
"use server";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
export async function switchLocale(next: string, currentPath: string) {
(await cookies()).set("lang", next, {
path: "/", maxAge: 60 * 60 * 24 * 365, sameSite: "lax",
});
const path = currentPath.replace(/^\/(en|ko|ja)/, "") || "/";
redirect(`/${next}${path}`);
}The middleware must treat a path that already has a locale as final, even when it disagrees with the cookie. Redirecting to the cookie's locale on every request makes the URL follow the user and breaks every shared link.
5. Dictionaries, plural rules, and interpolation
String concatenation across languages produces broken grammar. Use ICU messages so plural categories come from Intl.PluralRules for that locale — Korean has one plural form, Polish has four, and Arabic has six:
import { IntlMessageFormat } from "intl-messageformat";
const messages = {
en: "{count, plural, one {# post} other {# posts}}",
ko: "{count}개의 글",
pl: "{count, plural, one {# post} few {# posty} many {# postów} other {# postu}}",
};
export function posts(locale: string, count: number) {
return new IntlMessageFormat(messages[locale], locale).format({ count });
}Never build dates with manual month arrays either: new Intl.DateTimeFormat(locale, { dateStyle: "long" }) and Intl.NumberFormat(locale, { style: "currency", currency }) already encode the order and separators.
6. Localised 404, not-found.tsx, and metadata inheritance
A not-found.tsx inside app/[lang] renders with that locale's layout, so the copy is translated. But not-found cannot read params reliably when triggered from a layout, and notFound() thrown inside generateStaticParams produces a build error instead of a 404. Validate locales in the layout and return notFound() there; keep generateStaticParams limited to locales you actually ship.
Common Runtime & Configuration Mistakes
| Symptom | Cause | Fix |
|---|---|---|
| Assets 404 after adding locale redirect | Middleware matcher does not exclude _next and static files | Use the negative-lookahead matcher |
Every locale page renders as (Dynamic) | Library reads headers or cookies during render | Call setRequestLocale(lang) in each segment |
| Language flips back after clicking a link | Cookie overrides an explicit locale path | Treat locale-prefixed paths as authoritative in middleware |
| Duplicate content in Search Console | Unprefixed URL and prefixed URL both serve the page | 308 from unprefixed to default locale, canonical to prefixed |
| Mixed languages on one page | Some dictionaries imported at module scope from en | Resolve dictionary per request, never cache a module-level constant |
params.lang is a Promise complaint | Next.js 15 async params | const { lang } = await params in page, layout, and metadata |
Try matching browser tools
All toolsSmall utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Next.js guides
All Next.js guidesNext.js Static Export, Standalone Output, and Docker Deployment
Export has no server, standalone has a pruned one, and the default expects a full install. The three COPY lines that decide whether a container renders CSS.
Next.js Parallel Routes and Intercepting Routes: Slot Layouts and Modals
Named slots render several pages in one layout, and (.) interception makes a click open over the page while a direct link renders the full route. Why every slot needs default.tsx.
Next.js ISR: Route Revalidate, revalidateTag, and On-Demand Invalidation
Two clocks and one trigger: route revalidate seconds, fetch-level tags, and a webhook that calls revalidateTag. A timer is a ceiling on freshness, never a guarantee.
Next.js Environment Variables: NEXT_PUBLIC_, Build-Time Inlining, and Runtime Config
The prefix decides whether a value is compiled into the browser bundle or stays on the server. One image, two environments, and the choice that follows from it.
More in Next.js
All Next.js guidesThe guides filed next to this one in Next.js, in library order.