Skip to content

Lesson 17 of 27Full-stack

Internationalization in Next.js

Put the locale in the URL with app/[lang], negotiate it in proxy.ts, load dictionaries on the server, and tell search engines about every language.

16 min read0/4 questions

Your company sells in the UK and has just signed distributors in Germany and Poland. The product manager's ticket says "add German and Polish", as if it were a font change. It is not. Someone has to decide what the URLs look like, how a first-time visitor gets the right language, where the translations live and how much JavaScript they cost, how plurals work in a language with three plural forms, and how Google learns that /de/preise and /en/pricing are the same page. Internationalization (i18n) touches routing, caching, SEO and rendering at once, which is why it comes up in system design interviews for any company with customers abroad. Internationalization in React covered catalogs, ICU plurals and Intl formatting. This lesson adds what Next.js changes: locale URLs, server-side dictionaries and SEO.

Put the locale in the URL

There are three common ways to know which language to show:

  • A path prefix: acme.com/de/pricing. One domain, one deployment, simplest to run.
  • A domain or subdomain: acme.de/pricing or de.acme.com. Strong local signal, more DNS and certificate work.
  • No URL change: read a cookie or the browser's Accept-Language header and render a different language at the same URL.

The third option looks friendliest and causes the most trouble. If /pricing can be English or German depending on a header, then every CDN and cache in between must store separate copies keyed on that header (Vary: Accept-Language), and since browsers send hundreds of different header values, caches mostly give up. Search engines crawl mostly without a language preference, so they see one language and never index the others. And a user cannot share a German link with a German colleague, because the link does not say German.

So the rule seniors follow: every URL serves exactly one language. Detection can choose which URL to send someone to, but the URL then decides the language. That is a path prefix or a domain.

One trap from older tutorials: the i18n key in next.config (with locales and defaultLocale) is a Pages Router feature. The App Router ignores it. In the App Router you build i18n routing yourself with a dynamic segment and proxy.ts, or with a library that does it for you.

app/[lang] as the root segment

Put every route under a dynamic segment, and put the root layout inside it, so that it can set <html lang> per locale:

An App Router app with locale routing
  • app/
  • [lang]/
  • layout.tsxroot layout: <html lang dir>
  • page.tsx/de, /en, /pl
  • pricing/
  • page.tsx/de/pricing
  • dictionaries.tsgetDictionary(), server only
  • dictionaries/
  • en.json
  • de.json
  • pl.json
  • sitemap.ts
  • proxy.tspicks a locale for URLs without one
app/[lang]/layout.tsx
import { notFound } from "next/navigation";
import { hasLocale, LOCALES, isRtl } from "./dictionaries";
 
export async function generateStaticParams() {
  return LOCALES.map((lang) => ({ lang }));
}
 
export default async function RootLayout({ children, params }: LayoutProps<"/[lang]">) {
  const { lang } = await params;
  if (!hasLocale(lang)) notFound(); // /xx/pricing is a 404, not a crash
 
  return (
    <html lang={lang} dir={isRtl(lang) ? "rtl" : "ltr"}>
      <body>{children}</body>
    </html>
  );
}

generateStaticParams tells the build which locales exist, so every page is prerendered once per language. With Cache Components enabled, it is required for a root segment like [lang]: each root parameter needs at least one value or the build fails. Note that the old dynamicParams = false segment option is not available with Cache Components, which is why the hasLocale check and notFound() matter: they are how unknown locales become a 404.

The lang attribute is not decoration. Screen readers use it to choose a voice and pronunciation, browsers use it for hyphenation and spell checking, and translation tools use it to decide whether to offer a translation. Get it wrong and a German page is read aloud with English phonetics.

Not-found pages when the root layout is dynamic

With the root layout inside [lang], there is no layout above it for a URL that matches no route at all, so a plain app/not-found.tsx has nothing to render inside. Next.js has an experimental app/global-not-found.tsx (enabled with experimental.globalNotFound) for exactly this case. It renders a whole document on its own, so it must include its own <html>, styles and fonts. Inside a valid locale, a not-found.tsx in app/[lang]/ handles notFound() calls as usual.

Choosing the locale in proxy.ts

A visitor who types acme.com/pricing has no locale in the URL. proxy.ts (the Next.js 16 name for middleware, covered in Auth and Proxy) decides where to send them. Check signals in a fixed order, from most to least explicit:

Put it in order4 steps

Order the signals proxy should check when picking a locale, from first to last.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
proxy.ts
import { NextResponse, type NextRequest } from "next/server";
import { LOCALES, DEFAULT_LOCALE, negotiate } from "@/i18n/config";
 
export function proxy(request: NextRequest) {
  const { pathname } = request.nextUrl;
  const hasLocale = LOCALES.some((l) => pathname === `/${l}` || pathname.startsWith(`/${l}/`));
  if (hasLocale) return NextResponse.next();
 
  const fromCookie = request.cookies.get("NEXT_LOCALE")?.value;
  const locale =
    fromCookie && LOCALES.includes(fromCookie)
      ? fromCookie
      : negotiate(request.headers.get("accept-language"), LOCALES, DEFAULT_LOCALE);
 
  const url = request.nextUrl.clone();
  url.pathname = `/${locale}${pathname}`;
  return NextResponse.redirect(url); // 307: the address bar now shows /de/pricing
}
 
export const config = {
  matcher: ["/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt|.*\\..*).*)"],
};

negotiate parses the header. Accept-Language: de-AT,de;q=0.9,en;q=0.7 means "Austrian German, then any German, then English", with q values as weights. You want the highest-weighted entry you support, and a regional tag like de-AT should fall back to de. In production use a tested library (the Next.js docs show @formatjs/intl-localematcher with negotiator), but the logic is small enough to read:

TypeScriptnegotiate.ts
function negotiate(header: string | null, supported: string[], fallback: string): string { if (!header) return fallback; const wanted = header .split(",") .map((part) => { const [tag, ...params] = part.trim().split(";"); const q = params.find((p) => p.trim().startsWith("q=")); return { tag: tag.toLowerCase(), q: q ? Number(q.trim().slice(2)) : 1 }; }) .filter((w) => w.q > 0) .sort((a, b) => b.q - a.q); for (const { tag } of wanted) { if (supported.includes(tag)) return tag; // exact: "de" const base = tag.split("-")[0]; if (supported.includes(base)) return base; // regional fallback: "de-at" -> "de" } return fallback;} const supported = ["en", "de", "pl"];console.log(negotiate("de-AT,de;q=0.9,en;q=0.7", supported, "en"));console.log(negotiate("fr-FR,fr;q=0.9,pl;q=0.5", supported, "en"));console.log(negotiate("ja", supported, "en"));console.log(negotiate("en;q=0.2,pl;q=0.8", supported, "en"));
Output
Press Run (⌘ Enter) to see what happens.

Redirect or rewrite?

A redirect changes the address bar to /de/pricing. A rewrite serves /de/pricing while the address bar still says /pricing. Libraries offer a mode where the default locale has no prefix (/pricing is English, /de/pricing is German) using a rewrite for the default. That is fine, because /pricing still always means English. What you must not do is rewrite /pricing to a different language per visitor: that brings back every caching and SEO problem from the start of this lesson.

Also, only negotiate on URLs without a locale. Never redirect someone away from /en/pricing because their browser prefers German. They may have clicked the language switcher, or a colleague may have sent the English link on purpose. The language switcher sets the NEXT_LOCALE cookie (a Server Action can do that) and links to the same page in the other locale.

A German visitor's first request
Browserproxy.tsPage /de/pricingGET /pricing (Accept-Language: de-AT)307 Location: /de/pricingGET /de/pricingprerendered German HTML

No locale in the path and no cookie yet.

1/4
Quick check
A teammate proposes keeping URLs clean: proxy reads Accept-Language and rewrites /pricing to the matching locale, with no prefix in the address bar. What is the main problem?
Need a nudge? A hint rules out a wrong answer.

Dictionaries on the server

The simplest translation system is a JSON file per locale and a function that loads the right one:

app/[lang]/dictionaries.ts
import "server-only";
 
const dictionaries = {
  en: () => import("./dictionaries/en.json").then((m) => m.default),
  de: () => import("./dictionaries/de.json").then((m) => m.default),
  pl: () => import("./dictionaries/pl.json").then((m) => m.default),
};
 
export type Locale = keyof typeof dictionaries;
export const LOCALES = Object.keys(dictionaries) as Locale[];
export const hasLocale = (l: string): l is Locale => l in dictionaries;
export const isRtl = (l: string) => ["ar", "he", "fa", "ur"].includes(l.split("-")[0]);
export const getDictionary = (l: Locale) => dictionaries[l]();

Because pages and layouts are Server Components, the dictionary is read on the server and only the finished HTML goes to the browser. A 2,000-key translation file costs zero client JavaScript. That is a real advantage over classic single-page apps, which shipped every string for the current language in the bundle.

Client Components are the exception. A dropdown or a toast that needs translated text runs in the browser, so it needs the strings there too. Do not pass the whole dictionary as a prop; it would be serialized into the RSC payload on every page. Pass only the slice that component uses (dict.cart), or let a library such as next-intl provide the client messages for a specific namespace.

Typing the keys is cheap and catches typos at build time: treat en.json as the source of truth and declare type Dictionary = typeof import("./dictionaries/en.json"). A CI step that checks every other locale file has the same keys stops a release that would show raw keys like pricing.cta to Polish users.

Root params: the locale without prop drilling (16.3+)

Passing lang from the page through five layers of components gets old. Since Next.js 16.3, next/root-params gives you a getter for each dynamic segment above the root layout. With the root layout in app/[lang], you can import lang:

app/[lang]/dictionaries.ts
import { lang } from "next/root-params";
import { notFound } from "next/navigation";
 
export async function getDictionary() {
  const locale = await lang();
  if (!hasLocale(locale)) notFound();
  return dictionaries[locale]();
}

Now any Server Component calls await getDictionary() with no arguments. Two details are worth knowing for interviews and code review:

  • Inside a "use cache" function, Next.js tracks which root params you read and adds only those to the cache key. A cached navigation menu that reads lang() gets one entry per language, not one per page.
  • The getters work in Server Components and server utilities, but not in Client Components, Server Actions or (for now) Route Handlers. In an action, take the locale from a form field or the cookie, and validate it against your list.

Messages that are more than strings

Translations are not just word swaps. "You have 1 item" and "You have 5 items" need different forms, and English, with two forms, is the easy case. Polish has separate forms for 1, for 2 to 4, and for 5 and above (with exceptions in the teens). Arabic has six categories. Code like count === 1 ? "item" : "items" is wrong for most of the world.

The platform already knows the rules. Intl.PluralRules tells you which category a number falls into, and a message format such as ICU picks the text for that category:

TypeScriptplurals.ts
const messages: Record<string, Record<string, string>> = { en: { one: "# item", other: "# items" }, pl: { one: "# produkt", few: "# produkty", many: "# produktów", other: "# produktu" },}; function itemCount(locale: string, n: number) { const category = new Intl.PluralRules(locale).select(n); return messages[locale][category].replace("#", new Intl.NumberFormat(locale).format(n));} for (const n of [1, 2, 5, 22, 1500]) { console.log(String(n).padStart(4), itemCount("en", n).padEnd(12), itemCount("pl", n));}console.log(new Intl.PluralRules("ar").resolvedOptions().pluralCategories.join(", "));
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputTypeScript

What does this print?

const pl = new Intl.PluralRules("pl");
console.log([1, 3, 12, 24].map((n) => pl.select(n)).join(" "));
Need a nudge? Hints walk you through it.

Hand-rolling this for every message is where a library earns its place. next-intl is the most common choice for the App Router: ICU message syntax ({count, plural, one {# item} other {# items}}), formatting helpers for dates, numbers and relative times, typed keys, a proxy helper for locale routing, and APIs that work in both Server Components (getTranslations) and Client Components (useTranslations). Reach for it once you need plurals, rich text in messages, or many Client Components with translated text. For a marketing site with a few dozen strings, plain dictionaries are enough. Check the library's docs for the current setup, since its integration with Cache Components and root params has evolved release by release.

Dates and numbers follow the same principle: format with Intl.DateTimeFormat and Intl.NumberFormat using the page's locale, as covered in Dates, Time Zones and Intl. One Next.js-specific trap from that lesson matters doubly here: if a Client Component formats a date with the browser's default time zone while the server used UTC, the HTML and the hydrated output differ and React reports a hydration mismatch. Pass an explicit timeZone, or format on the server.

Never build sentences by concatenating translated fragments (t("hello") + " " + name + t("welcome")). Word order differs between languages, so give translators the whole sentence with a placeholder: "Welcome back, {name}".

SEO: hreflang and localized sitemaps

Search engines need to know that your English and German pricing pages are translations of each other, not duplicate content. That is what hreflang links do, and the Metadata API generates them from alternates.languages:

app/[lang]/pricing/page.tsx
import type { Metadata } from "next";
import { LOCALES } from "../dictionaries";
 
export async function generateMetadata({ params }: PageProps<"/[lang]/pricing">): Promise<Metadata> {
  const { lang } = await params;
  return {
    alternates: {
      canonical: `/${lang}/pricing`, // each language is canonical for itself
      languages: {
        ...Object.fromEntries(LOCALES.map((l) => [l, `/${l}/pricing`])),
        "x-default": "/en/pricing", // where to send users whose language you do not support
      },
    },
  };
}

With metadataBase set in the root layout, these become absolute <link rel="alternate" hreflang="de" href="https://acme.com/de/pricing"> tags. The common mistakes: pointing every locale's canonical at the English page (which tells Google to drop the translations), and forgetting that the links must be reciprocal, so every version lists every other version, including itself.

Sitemaps take the same map. Each entry in app/sitemap.ts can include alternates: { languages: { de: "https://acme.com/de/pricing", ... } }, so a crawler discovers every language from one file.

Match the pairs0/6 matched

Match each job to the Next.js feature or API that does it.

Choose an item, then its match on the other side.

Right-to-left and the rest of the checklist

Supporting Arabic or Hebrew means dir="rtl" on <html>, which flips the default text direction and the order of inline content. Layout flips only if your CSS lets it: use logical properties (margin-inline-start instead of margin-left, padding-inline, inset-inline-end, text-align: start). Tailwind has logical utilities such as ms-4, pe-2 and start-0, plus rtl: and ltr: variants for the rare cases like a directional arrow icon.

The rest of the list a senior brings to the kickoff meeting:

  • Text expansion. German strings often run a third longer than English ones. Buttons with fixed widths overflow. Test with real translations or a pseudo-locale that pads every string.
  • Translated slugs. /de/preise is nicer than /de/pricing but needs a slug map per locale and makes the language switcher look up the matching slug. Decide early.
  • Content vs UI strings. Dictionaries hold UI text. Blog posts and product descriptions belong in your CMS or database with a locale column, loaded through the same DAL as any other data.
  • Fonts. Make sure your next/font subsets cover the scripts you add, such as latin-ext for Polish characters.
Key terms
locale
An identifier for language and regional preferences, such as de, de-AT or en-GB.
Accept-Language
A request header listing the browser's preferred languages with q weights; a hint, not a choice the user made on your site.
root params
Dynamic segments above the root layout, readable from any Server Component via getters from next/root-params (Next.js 16.3+).
dictionary
A per-locale map from message keys to translated strings, loaded on the server.
ICU message format
A syntax for translatable messages with placeholders, plurals and selects, such as {count, plural, one {# item} other {# items}}.
hreflang
Alternate links that tell search engines which URL is each language version of a page.
logical properties
CSS properties like margin-inline-start that follow text direction, so layouts flip correctly in right-to-left languages.