Skip to content
Tutorials Center
My learning

Topics

Lesson 51 of 72 ยท Optimization and SEO

Internationalization

Build a multilingual Next.js site: locale in the URL, language detection in the proxy file, server-side dictionaries, hreflang tags and Intl formatting.

A site that speaks only one language leaves most of the world outside. Internationalization (often shortened to i18n, because there are 18 letters between the "i" and the "n") is the work of preparing an app for many languages and regions. Localization is the work of actually translating and adapting it for each one.

The Pages Router had an i18n option in its configuration. The App Router does not: you build the routing yourself, with tools you already know. A dynamic segment holds the locale, the proxy file picks a locale for visitors who do not specify one, server-only dictionaries hold the strings, and metadata tells search engines which page is which translation. This lesson walks through each step. Next.js code is read-only here because the framework cannot run on this site. Two Node stand-ins run the logic at the heart of the setup: choosing a locale from the Accept-Language header, and looking up and formatting translated text.

Four moving parts

Locale in the URL /en/about and /de/about, via a [lang] segment.
Detection The proxy picks a language for new visitors.
Dictionaries JSON files of strings, loaded on the server.
hreflang Tell search engines which page is which translation.
1 / 2

Putting the locale in the URL

The most common and search-friendly design is sub-path routing: every URL starts with the locale, such as /en/pricing and /de/pricing. Each language gets its own addresses, which can be cached, shared, linked to and indexed separately. The alternatives are separate domains (example.de) or a cookie with an unchanged URL; the cookie approach is simple but search engines then see only one version.

With the App Router, you put every route under a dynamic [lang] segment, as you saw in Dynamic Routes. The root layout moves into that folder:

TEXT
app/
  [lang]/
    layout.tsx        root layout: html, body, lang and dir
    page.tsx          the home page, in the visitor's language
    dictionaries.ts   loads the strings
    dictionaries/
      en.json
      de.json
    pricing/
      page.tsx
proxy.ts              redirects / to /en or /de

Because the root layout is now under [lang], it can set the language of the whole document, which matters for screen readers, spell checkers and browsers' translation prompts:

TSX
// app/[lang]/layout.tsx (read-only)
import { notFound } from "next/navigation";
import { hasLocale } from "@/app/[lang]/dictionaries";

export async function generateStaticParams() {
  return [{ lang: "en" }, { lang: "de" }, { lang: "ar" }];
}

export default async function RootLayout({
  children,
  params,
}: {
  children: React.ReactNode;
  params: Promise<{ lang: string }>;
}) {
  const { lang } = await params;
  if (!hasLocale(lang)) notFound();
  return (
    <html lang={lang} dir={lang === "ar" ? "rtl" : "ltr"}>
      <body>{children}</body>
    </html>
  );
}

Three things happen here. generateStaticParams lists the supported locales, so each page is prerendered once per language at build time (Static Generation and generateStaticParams). The hasLocale check returns a 404 for a made-up lang like /xx/pricing. And dir flips the layout direction for right-to-left languages. Using the locale from the URL keeps pages static; reading it from request headers inside a layout would make every page dynamic (see Static vs Dynamic Rendering).

Choosing a locale in the proxy file

A visitor who opens / or /pricing has not chosen a language. The proxy file (called middleware.ts in earlier versions; see Middleware and the Proxy File) runs before the request reaches a route, so it can look at the Accept-Language header the browser sends and redirect to the best match.

TypeScript
// proxy.ts (read-only)
import { NextRequest, NextResponse } from "next/server";
import Negotiator from "negotiator";
import { match } from "@formatjs/intl-localematcher";

const locales = ["en", "de", "ar"];
const defaultLocale = "en";

function getLocale(request: NextRequest): string {
  const saved = request.cookies.get("NEXT_LOCALE")?.value;
  if (saved && locales.includes(saved)) return saved;
  const headers = { "accept-language": request.headers.get("accept-language") ?? "" };
  const languages = new Negotiator({ headers }).languages();
  return match(languages, locales, defaultLocale);
}

export function proxy(request: NextRequest) {
  const { pathname } = request.nextUrl;
  const hasLocale = locales.some((l) => pathname === `/${l}` || pathname.startsWith(`/${l}/`));
  if (hasLocale) return;

  request.nextUrl.pathname = `/${getLocale(request)}${pathname}`;
  return NextResponse.redirect(request.nextUrl);
}

export const config = {
  matcher: ["/((?!_next|api|.*\\..*).*)"],
};

The matcher skips internal files, API routes and anything with a dot (images, fonts, favicon.ico), so only page URLs are redirected. Notice the order of preference: a saved choice in a cookie wins over the browser's language, so a user who picks German on an English-language browser keeps German.

The Accept-Language header looks like de-AT,de;q=0.9,en;q=0.8. Each entry is a language tag with an optional quality weight q between 0 and 1 (1 when missing). The stand-in below implements the same decision with a few lines: parse and sort the header, match each tag against the supported list (ignoring the region if needed), and fall back to the default.

Node.js Choosing a locale from Accept-Language

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the results: de-AT has no exact match, so the region is dropped and de wins. French is unsupported, but English is in the list with a lower weight, so English is chosen. Japanese has nothing in common with the supported set, so the default applies. The cookie overrides the header, and a URL that already starts with a locale is left alone. A request without any header, such as a search crawler's, gets the default language.

Dictionaries on the server

A dictionary is a JSON file of strings for one locale, with the same keys in every file:

JSON
{
  "home": { "title": "Welcome", "cta": "Start free" },
  "cart": { "items": { "one": "{count} item", "other": "{count} items" } }
}

A small module loads the right one. Each file is imported dynamically, so only the requested language is read. Mark the module server-only so no dictionary can end up in a Client Component's bundle (see Keeping Server Code on the Server):

TypeScript
// app/[lang]/dictionaries.ts (read-only)
import "server-only";

const dictionaries = {
  en: () => import("./dictionaries/en.json").then((m) => m.default),
  de: () => import("./dictionaries/de.json").then((m) => m.default),
  ar: () => import("./dictionaries/ar.json").then((m) => m.default),
};

export type Locale = keyof typeof dictionaries;

export const hasLocale = (value: string): value is Locale => value in dictionaries;

export const getDictionary = async (locale: Locale) => dictionaries[locale]();

A Server Component then uses it like any other async data:

TSX
// app/[lang]/page.tsx (read-only)
import { notFound } from "next/navigation";
import { getDictionary, hasLocale } from "./dictionaries";

export default async function Home({ params }: { params: Promise<{ lang: string }> }) {
  const { lang } = await params;
  if (!hasLocale(lang)) notFound();
  const dict = await getDictionary(lang);
  return (
    <main>
      <h1>{dict.home.title}</h1>
      <a href={`/${lang}/signup`}>{dict.home.cta}</a>
    </main>
  );
}

Since the dictionary stays on the server, the browser receives only the finished text. If a Client Component needs a few strings, pass exactly those as props instead of the whole dictionary (Composing Server and Client Components).

Placeholders, plurals and formatting

Never build sentences by joining pieces: word order differs between languages, and "1 items" is wrong. Keep whole sentences in the dictionary with placeholders, and choose plural forms with Intl.PluralRules, which knows each language's rules. For numbers, dates and lists, use the built-in Intl formatters with the current locale instead of hand-written patterns.

The stand-in below is a tiny translate function with interpolation, plural selection and a fallback to the default language when a key is missing, followed by Intl formatting for three locales. The code is small on purpose; a library such as next-intl gives you a richer message syntax with the same ideas.

Node.js Looking up and formatting messages

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Check the details: English picks one for 1 and other for 5; German has the same count word in both forms; Japanese has only an other form, so the fallback message.other handles every count. The missing English-only key falls back to English in de and ja, and an unknown key is reported instead of crashing. In the formatting section the same number and date look different per locale: that is what Intl is for.

Telling search engines about translations

Search engines must learn that /en/pricing and /de/pricing are the same page in different languages, or they may show the wrong one. Use the alternates field from Metadata and SEO to produce hreflang links, and include a self-referencing canonical URL:

TSX
// app/[lang]/pricing/page.tsx (read-only)
import type { Metadata } from "next";

export async function generateMetadata({ params }: { params: Promise<{ lang: string }> }): Promise<Metadata> {
  const { lang } = await params;
  return {
    alternates: {
      canonical: `/${lang}/pricing`,
      languages: {
        en: "/en/pricing",
        de: "/de/pricing",
        "x-default": "/en/pricing",
      },
    },
  };
}

x-default marks the page to show when no listed language fits. Every translation should list all the others, including itself. Add each locale's URLs to the sitemap as well.

Libraries and other choices

You do not have to write all of this yourself. next-intl is a popular library built for the App Router, with routing helpers, ICU message syntax (plurals, selects, rich text), and localized Link components. Others include react-i18next and Lingui. They all follow the same ideas you have now seen: a locale in the route, messages loaded per locale, and Intl for formatting. Whichever you choose, keep these habits: write translatable sentences as complete units, avoid hard-coded text in components, test one right-to-left locale early, and leave room for text that is 30 to 40 percent longer than English.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How do you add locale-based routing in the App Router?

    The App Router has no built-in i18n routing option. A dynamic locale segment plus a proxy redirect is the standard approach.
  2. 2. A visitor's browser sends Accept-Language: de-AT,de;q=0.9,en;q=0.8 and your site supports en and de. Which locale is chosen?

    de-AT is not supported exactly, but its base language de is, and it ranks above en by quality.
  3. 3. Why mark a dictionary loader module with server-only?

    Keeping dictionaries on the server means the browser only receives rendered text. server-only makes the build fail if a Client Component imports the module.
  4. 4. What is the purpose of hreflang alternates?

    hreflang links connect the language versions so search engines can show each user the right one.
  5. 5. Why use Intl.PluralRules instead of count === 1 ? 'item' : 'items'?

    Languages differ: some have one form, some have several. PluralRules returns the right category for the locale.

Summary

  • The App Router has no i18n option; use a [lang] segment, generateStaticParams for the locales and a 404 for unknown ones.
  • Set lang and dir on the <html> element from the route.
  • The proxy file redirects locale-less URLs using a saved cookie first, then Accept-Language, then a default.
  • Keep dictionaries in server-only modules, load them per locale, and pass only needed strings to Client Components.
  • Use complete sentences with placeholders, Intl.PluralRules for plurals and Intl formatters for numbers and dates.
  • Publish alternates.languages (hreflang) and a canonical URL for every translation; consider a library such as next-intl for richer features.

Next: Configuring Next.js