Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~4 min readNext.js
#Next.js#i18n#Routing#SEO
3D illustration of a globe with locale URL segments branching into dictionary folders

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

tsx
// 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> ); }
ts
// 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:

ts
// 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

StrategyURL shapeSEOStatic per localeCost
Sub-path /[lang]/...example.com/ko/blogStrong, simpleYesLowest; one deployment
Sub-domain ko.example.comko.example.com/blogStrong, separate hostsYesDNS plus per-host build or rewrite
Cookie or header onlyexample.com/blogWeak — one URL, many languagesNo, dynamicSimplest URLs, worst caching
Domain per marketexample.krStrong, strongest signalsYesHighest; separate properties
Client-only switchexample.com/blogPoor, no per-locale URLNoCheapest, not indexable per locale
LibraryLocale sourceStatic renderingFormatting (dates, plurals)
Hand-rolled dictionariesRoute paramYesManual, Intl
next-intlRoute param or requestYes, with setRequestLocaleICU messages built in
react-i18nextProvider in client treeLimited; mostly clienti18next 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:

tsx
// 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.

tsx
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:

ts
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:

ts
"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:

ts
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

SymptomCauseFix
Assets 404 after adding locale redirectMiddleware matcher does not exclude _next and static filesUse the negative-lookahead matcher
Every locale page renders as (Dynamic)Library reads headers or cookies during renderCall setRequestLocale(lang) in each segment
Language flips back after clicking a linkCookie overrides an explicit locale pathTreat locale-prefixed paths as authoritative in middleware
Duplicate content in Search ConsoleUnprefixed URL and prefixed URL both serve the page308 from unprefixed to default locale, canonical to prefixed
Mixed languages on one pageSome dictionaries imported at module scope from enResolve dictionary per request, never cache a module-level constant
params.lang is a Promise complaintNext.js 15 async paramsconst { lang } = await params in page, layout, and metadata

Try matching browser tools

All tools

Small utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Next.js guides

More in Next.js

All Next.js guides

The guides filed next to this one in Next.js, in library order.