🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Locale Routing and i18n in the App Router

Next.js FeaturesđŸŸĸ Free Lesson

Locale Routing and i18n in the App Router

Internationalization is routing, content, and formatting solved together. A visitor arriving from Spain should land on Spanish URLs, read translated copy with the same layout the English version uses, see dates and currency in their conventions, and switch languages without losing their place. Next.js does not ship a built-in i18n router in the App Router the way it did for the pages directory, but the pieces — a [locale] segment, middleware for negotiation, translation catalogs, and the Intl API — compose into something more flexible than the old configuration ever was.

This lesson builds that stack end to end: how to structure the locale segment, how middleware negotiates the first visit, how translations stay out of the client bundle, how right-to-left languages change layout, and how to format dates, numbers, and currencies per locale without pulling in a heavy library.

Prerequisites

  • !Dynamic segments and layouts from the routing lesson
  • !Middleware basics: redirects and cookies
  • !JSON data files and module imports

What You'll Learn

  • 1Structure an app around a [locale] dynamic segment
  • 2Negotiate locale in middleware with cookie and header signals
  • 3Load translation catalogs per request without bloating the client
  • 4Flip document direction and formatting for RTL and locale conventions

The locale segment structure

Every route lives under [locale], and the root layout for that segment sets the html lang and dir attributes. A validation helper rejects unknown locales with notFound(), so /xx/about is a proper 404 rather than a half-rendered page.

// app/[locale]/layout.js
import { notFound } from 'next/navigation';
import { getDictionary } from '@/lib/dictionaries';

const locales = ['en', 'es', 'fr'];

export function generateStaticParams() {
  return locales.map((locale) => ({ locale }));
}

export default async function LocaleLayout({ children, params }) {
  const { locale } = await params;
  if (!locales.includes(locale)) notFound();

  const dict = await getDictionary(locale);
  const dir = locale === 'ar' ? 'rtl' : 'ltr';

  return (
    <html lang={locale} dir={dir}>
      <body>
        <nav aria-label="Main">
          <a href={`/${locale}`}>{dict.nav.home}</a>
          <a href={`/${locale}/pricing`}>{dict.nav.pricing}</a>
        </nav>
        <main>{children}</main>
      </body>
    </html>
  );
}

The generateStaticParams call means the build prerenders one page tree per locale — the cheapest possible serving model for the common case. Pages that read cookies or searchParams can still opt into dynamic rendering where personalization demands it. Keeping the locale list in one shared module — imported by the layout, the middleware, and the metadata helpers — prevents the classic drift where a new language works in navigation but 404s on direct load.

Negotiating the first visit

Users arrive at the bare root, and someone has to decide which locale greets them. Middleware is the right place: check an explicit cookie set by a language picker, then the Accept-Language header, then fall back to the default, and redirect once. Persisting the choice in a cookie means subsequent visits skip the negotiation entirely.

javascript
// middleware.js
import { NextResponse } from 'next/server';

const locales = ['en', 'es', 'fr'];
const defaultLocale = 'en';

function matchLocale(header) {
  const candidates = header
    ?.split(',')
    .map((part) => {
      const [tag, q] = part.trim().split(';q=');
      return { tag: tag.split('-')[0], q: q ? Number(q) : 1 };
    })
    .sort((a, b) => b.q - a.q)
    .map((c) => c.tag);

  return candidates?.find((tag) => locales.includes(tag));
}

export function middleware(request) {
  const { pathname } = request.nextUrl;

  const cookieLocale = request.cookies.get('locale')?.value;
  const headerLocale = matchLocale(request.headers.get('accept-language'));

  const locale =
    [cookieLocale, headerLocale, defaultLocale].find((l) => locales.includes(l)) ??
    defaultLocale;

  const hasLocale = locales.some(
    (l) => pathname === `/${l}` || pathname.startsWith(`/${l}/`)
  );
  if (hasLocale) return NextResponse.next();

  const url = request.nextUrl.clone();
  url.pathname = `/${locale}${pathname === '/' ? '' : pathname}`;
  return NextResponse.redirect(url);
}

export const config = {
  matcher: ['/((?!_next|api|favicon.ico|robots.txt).*)'],
};

Quality values in Accept-Language matter: a Swiss user listing de-CH;q=0.9, fr;q=0.8 genuinely prefers German, and sorting by q before filtering avoids picking a low-priority tag that happens to appear first. After the first visit, the cookie wins on every subsequent request, which makes the language picker authoritative even when the browser's header disagrees.

Keeping translations out of the client bundle

A dictionary lookup belongs where the data is rendered. Loading the catalog inside a Server Component and passing strings down as props keeps the JSON on the server; only the components that need interactivity cross the boundary, and they receive the strings they display as ordinary props.

// lib/dictionaries.js
const dictionaries = {
  en: () => import('@/dictionaries/en.json').then((m) => m.default),
  es: () => import('@/dictionaries/es.json').then((m) => m.default),
  fr: () => import('@/dictionaries/fr.json').then((m) => m.default),
};

export async function getDictionary(locale) {
  return (dictionaries[locale] ?? dictionaries.en)();
}
{
  "nav": { "home": "Inicio", "pricing": "Precios" },
  "pricing": {
    "title": "Planes simples",
    "cta": "Empieza gratis"
  },
  "product": {
    "count_one": "un producto",
    "count_other": "{{count}} productos"
  }
}

Dynamic imports per locale mean each rendered page ships only its own catalog, not all three concatenated. For apps with dozens of languages, switch to lazy-loaded dictionaries keyed by locale and consider splitting long catalogs per route. Keeping keys hierarchical — nav, pricing, product — makes those splits mechanical when the time comes and gives translators file-like context for where each string appears.

Plurals, interpolation, and the Intl API

String concatenation falls apart past English. Plural rules differ per language — Arabic has six forms, Polish two for non-integers — so use Intl.PluralRules or a small library rather than ternaries. Dates, numbers, and currency have first-class support in the platform and need no dependency at all.

// app/[locale]/pricing/page.js
import { getDictionary } from '@/lib/dictionaries';

export default async function PricingPage({ params }) {
  const { locale } = await params;
  const dict = await getDictionary(locale);

  const price = new Intl.NumberFormat(locale, {
    style: 'currency',
    currency: locale === 'es' ? 'EUR' : 'USD',
  }).format(29);

  const releaseDate = new Intl.DateTimeFormat(locale, {
    dateStyle: 'long',
  }).format(new Date('2026-03-14'));

  const itemCount = new Intl.PluralRules(locale).select(12);

  return (
    <section>
      <h1>{dict.pricing.title}</h1>
      <p>{dict.pricing.cta}</p>
      <p>{price} / month</p>
      <p>Next release: {releaseDate}</p>
      <p>{dict.product[`count_${itemCount}`].replace('{{count}}', '12')}</p>
    </section>
  );
}

Currency selection deserves thought beyond the locale string: a Spanish-speaking visitor in Mexico should see MXN, not EUR, so tie currency to a market or user preference rather than deriving it from the URL locale alone.

Right-to-left layout without a second codebase

Arabic and Hebrew layouts mirror horizontally. Setting dir="rtl" on the html element flips the direction of flow for the entire document, and logical CSS properties — margin-inline-start, padding-inline, text-align: start — follow automatically. Physical properties such as margin-left do not, which is why migrating to logical properties early pays off.

/* globals.css — logical properties mirror for free */
.card {
  padding-inline: 1.5rem;
  margin-inline-start: auto;
  border-inline-start: 3px solid var(--color-brand);
  text-align: start;
}

.nav-cta {
  margin-inline-start: 1rem;
}

Icons that indicate direction — back arrows, steppers, carousels — need explicit flipping with transform: scaleX(-1) under [dir='rtl'] or a mirrored asset. Layout, type, and spacing usually take care of themselves once logical properties are in place.

hreflang and canonical discipline

Every locale page should declare its alternates so search engines index the right language per region and do not treat near-identical pages as duplicates. The Metadata API's alternates.languages maps locale codes to absolute URLs, and generateMetadata reads the locale from params the same way the page does.

// app/[locale]/pricing/page.js — metadata
export async function generateMetadata({ params }) {
  const { locale } = await params;
  const languages = {
    en: 'https://www.example.com/en/pricing',
    es: 'https://www.example.com/es/pricing',
    fr: 'https://www.example.com/fr/pricing',
    'x-default': 'https://www.example.com/en/pricing',
  };

  return {
    alternates: {
      canonical: languages[locale],
      languages,
    },
  };
}

Production pitfalls

The failure modes are cultural as much as technical. Shipping machine-translated strings without review. Hard-coding English date formats into PDFs generated server-side. Forgetting that a language picker is a preference that must persist — a cookie with a sensible max-age — so every navigation does not renegotiate. And the layout bug that only appears in Arabic: a fixed-width sidebar with margin-left that now sits on the wrong side, discovered by a user rather than a test. RTL visual regression belongs in the test suite alongside every other locale you claim to support.

Operating a translation workflow

Code is the easy part of internationalization; keeping translations current is the operating challenge. Treat dictionary files as versioned artifacts with the same review discipline as code: a missing key should fail the build in CI rather than render a raw undefined in production, and a translator's change should go through the same pull request process as a logic change so visual regression can catch overflow in longer German strings. Extract placeholders in a consistent syntax — double curly braces are a common choice — and lint for keys referenced in code but absent from each locale file. For larger catalogs, split by route or domain so a pricing page does not pay the bytes for the admin dictionary, and record a last-updated timestamp per locale so the team can see which languages are drifting. Finally, decide who owns each locale. Machine translation is a reasonable bootstrap; unreviewed machine translation in front of paying customers is a brand incident waiting for a screenshot. The workflow you build around the JSON files determines whether the i18n investment compounds or quietly rots.

Common Mistakes

Deriving currency from the URL locale

Fix: Use a market or account preference for currency; the locale controls language, not always the money a visitor pays in.

Concatenating translations with string addition

Fix: Use plural rules and interpolation placeholders so languages with different plural forms render correctly.

Using margin-left and right instead of logical properties

Fix: Switch to margin-inline and padding-inline so RTL layouts mirror without per-property overrides.

Loading every locale dictionary into the client bundle

Fix: Import the catalog per locale inside Server Components so each page ships only its own strings.

Best Practices

  • Persist the chosen locale in a cookie and honor it before Accept-Language
  • Add generateStaticParams so the build prerenders each locale's pages
  • Test at least one RTL locale in visual regression whenever layout changes ship
  • Declare alternates.languages and x-default so search engines map locales correctly

Interview Questions

Q1: Why put the locale in the URL instead of detecting it only from headers?

URL locales are shareable, indexable per language, and survive cookie clearing; middleware negotiation on first visit then redirects into the right canonical address.

Q2: How do you keep translation JSON out of the client bundle?

Load dictionaries with dynamic imports inside Server Components and pass strings down as props; only interactive children that need strings cross the boundary.

Q3: What do logical CSS properties change about RTL?

margin-inline-start, padding-inline, and text-align: start mirror automatically when dir becomes rtl, so one stylesheet serves both directions.

Key Takeaways

  • A [locale] segment plus a validating root layout gives every language its own prerendered tree.
  • Middleware negotiates once using cookie, then Accept-Language quality values, then a default.
  • Load dictionaries per locale on the server and pass strings as props to keep bundles lean.
  • Intl handles plurals, dates, and currency; logical CSS properties handle RTL mirroring.
  • Declare hreflang alternates per locale so search engines do not treat translations as duplicates.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Next.js Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement