Skip to content

Optional analytics, session recording and advertising stay off unless you accept. You can reject them and use Transglot. Change your choice anytime in Cookie preferences. Cookie Policy

Back to the blog
Developer platform

Next.js Localization: The Complete i18n Guide (2026)

Next.js i18n for the App Router: the locale segment, proxy.ts detection, next-intl setup, ICU plurals, hreflang, right to left, tests, CI and AI checks.

by transglot team
published November 24, 2026
27 min read

Documentation reviewed 23 November 2026.

Quick answer

Next.js localization in the App Router has no config switch. You put every route under a dynamic app/[locale] segment, detect the visitor's language from the Accept-Language header in proxy.ts (the file called middleware.ts before Next.js 16), and redirect to a prefixed URL such as /de/pricing. Translations are loaded on the server, either from plain JSON dictionaries or through a library. Most App Router projects use next-intl, which adds ICU plurals, date and number formatting, typed keys, locale-aware navigation and hreflang headers. Pre-render each language with generateStaticParams, and set lang, dir and alternate links per locale. The older Pages Router has a built-in i18n option in next.config.js that the App Router does not use.

What you will have at the end

The samples target Next.js 16.4 and next-intl 4.16, the current stable releases on npm at the review date. In Next.js 16 the request interception file is proxy.ts, with an exported function named proxy. The middleware name is deprecated.

By the end you will have:

  • Every page available at one URL per language, pre-rendered at build time.
  • Language detection on the root URL, and a switcher that keeps the current page.
  • Messages with correct plurals for languages with three, four or six forms.
  • Dates, numbers, currency and relative time formatted per locale.
  • Message keys checked by TypeScript.
  • Titles, hreflang links, a localized sitemap and Open Graph locale per language.
  • A right to left layout and fonts for non-Latin scripts.
  • Tests and a CI job that fail on a missing or malformed translation.
  • A way to translate ICU messages with AI and check what comes back.

This guide is for developers who own the Next.js codebase. For the short version of the translation step alone, see how to translate a React or Next.js app automatically. This guide does not repeat it.

A cream paper-pulp signpost on a stone plinth with three arms pointing to three paper doorways, each labelled with a language code
One request, one negotiated locale, one prefixed URL per language

Part 1: how App Router i18n works without a library

The Next.js internationalization guide describes three pieces: a [lang] or [locale] segment, a redirect in Proxy, and dictionaries loaded on the server. It is worth building once by hand, because every library does the same three things.

Detect the locale and redirect

The guide negotiates the locale with two small packages, negotiator and @formatjs/intl-localematcher.

proxy.ts, in the project root or in src/ts
import { match } from '@formatjs/intl-localematcher'
import Negotiator from 'negotiator'
import { NextResponse, type NextRequest } from 'next/server'
const locales = ['en', 'de', 'ar']
const defaultLocale = 'en'
function getLocale(request: NextRequest) {
const header = request.headers.get('accept-language') ?? ''
const languages = new Negotiator({
headers: { 'accept-language': header },
}).languages()
try {
return match(languages, locales, defaultLocale)
} catch {
return defaultLocale
}
}
export function proxy(request: NextRequest) {
const { pathname } = request.nextUrl
const hasLocale = locales.some(
(locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
)
if (hasLocale) return
request.nextUrl.pathname = `/${getLocale(request)}${pathname}`
return NextResponse.redirect(request.nextUrl)
}
export const config = {
matcher: [
'/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)',
],
}

The matcher is the negative pattern from the Proxy reference. Without a matcher, Proxy runs on every request, including static files and images, and a locale redirect would break them.

The try block is not in the Next.js sample. In a test for this guide, match() threw a RangeError when the header was Accept-Language: *, which some HTTP clients and crawlers send. With the fallback it returned en. A header of de-AT,de;q=0.9,en;q=0.8 returned de, and fr-FR returned the default.
Watch out

Middleware or proxy

Next.js versionFileExported functionRuntime
12.2 to 15middleware.tsmiddlewareThe Node.js runtime is stable from 15.5
16 and laterproxy.tsproxy, or a default exportNode.js by default. The runtime option is not available

The codemod npx @next/codemod@canary middleware-to-proxy . renames the file and the function. Proxy is not supported with static export.

Load dictionaries on the server

app/[lang]/dictionaries.tsts
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 = (locale: string): locale is Locale =>
locale in dictionaries
export const getDictionary = async (locale: Locale) => dictionaries[locale]()
app/[lang]/page.tsxtsx
import { notFound } from 'next/navigation'
import { getDictionary, hasLocale } from './dictionaries'
export default async function Page({ params }: PageProps<'/[lang]'>) {
const { lang } = await params
if (!hasLocale(lang)) notFound()
const dict = await getDictionary(lang)
return <button>{dict.products.cart}</button>
}

params is a promise and has to be awaited. PageProps and LayoutProps are global type helpers, so there is nothing to import. Pages are Server Components by default, so the dictionary runs only on the server and only the resulting HTML reaches the browser.

Since Next.js 16.3 the next/root-params module exposes the segment as a function, import { lang } from 'next/root-params', that any Server Component can call. It does not work in Client Components, Server Actions or Route Handlers.

Static rendering with `generateStaticParams`

app/[lang]/layout.tsxtsx
export async function generateStaticParams() {
return [{ lang: 'en' }, { lang: 'de' }, { lang: 'ar' }]
}
export default async function RootLayout({
children,
params,
}: LayoutProps<'/[lang]'>) {
return (
<html lang={(await params).lang}>
<body>{children}</body>
</html>
)
}

The root layout moves inside the segment, which is how <html lang> gets the right value.

StaticDynamic
When HTML is producedAt build time, once per locale returned by generateStaticParamsOn each request
What triggers itA locale that comes only from the URLReading cookies() or headers() while rendering
Locales not returnedRendered on first visit. export const dynamicParams = false makes them a 404, an option available only without Cache ComponentsNot applicable
Keep the locale in the URL and read nothing else to decide the language of a page. A page that reads a cookie to pick its language cannot be pre-rendered.
Rule

Dictionaries stop here. There are no plurals, no number or date formatting, no translation hook for Client Components and no typed keys. That gap is why most projects add a library.


Part 2: choose a library

Each row below was read on the library's own documentation. None was benchmarked.

LibraryMessage formatHow it fits Next.jsFits
Built-in dictionariesPlain JSON, your own shapeServer Components only, as in Part 1Small sites with a few static strings and no plurals
next-intl 4ICU messages in JSONuseTranslations in Server and Client Components, routing, navigation and hreflang headersApp Router projects that want one library for messages and routing
next-i18next 16, on react-i18nexti18next JSONVersion 16 covers the App Router, the Pages Router and mixed setups, with getT() on the server and useT() on the clientTeams already on i18next, or sharing translation files with a non-Next app
Paraglide JS 2 (inlang)inlang message files such as messages/en.jsonA compiler turns each message into a typed function, m.greeting({ name }). On the server the locale is passed explicitly. The Webpack plugin needs the --webpack flagApps that want unused messages removed from the bundle and typos as compile errors
LinguiICU, in PO catalogs by defaultText is wrapped in Trans and t macros, and ids are generated from the source text. The App Router tutorial uses the SWC plugin and a setup call in every layout and pageTeams that prefer writing source text in components over naming keys

The rest of this guide uses next-intl. The routing and SEO parts apply to all of them.


Part 3: next-intl setup in full

bashbash
npm install next-intl

Seven files make up the setup. The paths assume a src folder.

1. Messages

messages/en.jsonjson
{
"Cart": {
"greeting": "Welcome back, {name}",
"items": "{count, plural, =0 {Your cart is empty} one {# item in your cart} other {# items in your cart}}",
"terms": "By ordering you accept the <link>terms of service</link>.",
"shipped": "{gender, select, female {She shipped it} male {He shipped it} other {They shipped it}} on {date, date, medium}",
"total": "Total: {amount, number, ::currency/EUR}"
},
"Metadata": {
"title": "Parcel Desk",
"description": "Send and track parcels"
}
}

2. The plugin

next.config.tsts
import type { NextConfig } from 'next'
import createNextIntlPlugin from 'next-intl/plugin'
const nextConfig: NextConfig = {}
const withNextIntl = createNextIntlPlugin()
export default withNextIntl(nextConfig)

The plugin links src/i18n/request.ts to the library.

3. Routing config with `defineRouting`

src/i18n/routing.tsts
import { defineRouting } from 'next-intl/routing'
export const routing = defineRouting({
locales: ['en', 'de', 'ar'],
defaultLocale: 'en',
})

The option that shapes your URLs is localePrefix:

localePrefixURLsNotes
'always' (default)/en/about, /de/aboutEvery language is treated the same
'as-needed'/about, /de/aboutThe default locale has no prefix. The matcher must cover unprefixed paths
'never'/about for every languageRequests are rewritten internally and alternate links are turned off

4. Proxy

src/proxy.ts (middleware.ts before Next.js 16)ts
import createMiddleware from 'next-intl/middleware'
import { routing } from './i18n/routing'
export default createMiddleware(routing)
export const config = {
matcher: '/((?!api|trpc|_next|_vercel|.*\\..*).*)',
}

The import is still next-intl/middleware. It resolves the locale in this order: a prefix in the path, a cookie from an earlier visit, the Accept-Language header, then defaultLocale. The header is matched with the "best fit" algorithm of @formatjs/intl-localematcher, which the documentation notes can match en-GB to en-US where a strict lookup would fall through to the default.

The cookie is named NEXT_LOCALE. It is a session cookie, and it is set only when a visitor switches to a locale that differs from their Accept-Language header.

5. Navigation wrappers

src/i18n/navigation.tsts
import { createNavigation } from 'next-intl/navigation'
import { routing } from './routing'
export const { Link, redirect, usePathname, useRouter, getPathname } =
createNavigation(routing)

Import Link and useRouter from this file, not from next/link and next/navigation, so every internal link carries the current locale.

6. Request config

src/i18n/request.tsts
import * as rootParams from 'next/root-params'
import { notFound } from 'next/navigation'
import { hasLocale } from 'next-intl'
import { getRequestConfig } from 'next-intl/server'
import { routing } from './routing'
export default getRequestConfig(async ({ locale }) => {
if (!locale) {
const paramValue = await rootParams.locale()
if (hasLocale(routing.locales, paramValue)) {
locale = paramValue
} else {
notFound()
}
}
return {
locale,
messages: (await import(`../../messages/${locale}.json`)).default,
timeZone: 'Europe/Berlin',
}
})

This runs once per request, the first time a component asks for a translation. Set timeZone explicitly. Without it, dates are formatted in the server's time zone.

7. The locale layout

src/app/[locale]/layout.tsxtsx
import { NextIntlClientProvider } from 'next-intl'
import { getLocale } from 'next-intl/server'
import { routing } from '@/i18n/routing'
const RTL = ['ar', 'he', 'fa', 'ur']
export function generateStaticParams() {
return routing.locales.map((locale) => ({ locale }))
}
export default async function LocaleLayout({
children,
}: LayoutProps<'/[locale]'>) {
const locale = await getLocale()
return (
<html lang={locale} dir={RTL.includes(locale) ? 'rtl' : 'ltr'}>
<body>
<NextIntlClientProvider>{children}</NextIntlClientProvider>
</body>
</html>
)
}

Static rendering: `next/root-params` or `setRequestLocale`

With the request config above, the documentation says the app is eligible for static rendering once generateStaticParams is in place. That path needs Next.js 16.3 or later.

On older versions, next-intl reads the locale from a request header, and reading headers makes the route dynamic. setRequestLocale is the documented way around it. The next-intl documentation now labels it legacy, and it is still supported:

src/app/[locale]/cart/page.tsx, for Next.js before 16.3tsx
import { use } from 'react'
import { useTranslations } from 'next-intl'
import { setRequestLocale } from 'next-intl/server'
export default function CartPage({ params }: PageProps<'/[locale]/cart'>) {
const { locale } = use(params)
setRequestLocale(locale)
const t = useTranslations('Cart')
return <h1>{t('greeting', { name: 'Ada' })}</h1>
}

It has to be called in every layout and page that should be static, and before any next-intl function.


Part 4: translations in Server and Client Components

ComponentAPIImport
Server Component, not asyncuseTranslations('Cart')next-intl
Server Component, asyncawait getTranslations('Cart')next-intl/server
Client ComponentuseTranslations('Cart')next-intl
generateMetadata, Server Actions, Route Handlersawait getTranslations({ locale, namespace })next-intl/server

The same split exists for useFormatter and getFormatter, useLocale and getLocale, useNow and getNow.

NextIntlClientProvider passes the locale, messages, time zone and formats to Client Components. When a Server Component renders it, those values are inherited without props, and every message is sent to the browser. To send less, pass a subset, or messages={null} and hand translated strings to Client Components as props. Functions such as onError are not inherited, because they cannot cross the server boundary.


Part 5: ICU messages and formatting

next-intl messages use ICU syntax. The outputs below come from running the messages in Part 3 through the library's core with Node.js 22.

Plurals

tsts
t('items', { count: 0 }) // "Your cart is empty"
t('items', { count: 1 }) // "1 item in your cart"
t('items', { count: 3 }) // "3 items in your cart"

# prints the number, formatted for the locale. The category names are zero, one, two, few, many and other, and =0 is an exact match that wins over a category. Which categories a language uses comes from Intl.PluralRules:

LanguageCategoriesForms
Japaneseother1
English, Germanone, other2
Russian, Polishone, few, many, other4
Arabiczero, one, two, few, many, other6

The Russian message needs all four:

messages/ru.jsonjson
{
"Cart": {
"items": "{count, plural, =0 {Корзина пуста} one {# товар в корзине} few {# товара в корзине} many {# товаров в корзине} other {# товара в корзине}}"
}
}

It printed "1 товар в корзине", "3 товара в корзине", "5 товаров в корзине" and "21 товар в корзине". Ordinals use selectordinal with the same categories.

Cream paper-pulp tiles on a stone plinth arranged in three rows of two, four and six, each row inside a pair of paper braces
An ICU plural carries one branch per category the language uses

Select

{gender, select, female {...} male {...} other {...}} picks a branch by string value. The other branch is required. Branch names are identifiers, not text, and they stay in English in every language file.

Rich text

Tags in a message map to functions at the call site. Attributes such as href stay in code:

tsxtsx
t.rich('terms', {
link: (chunks) => <Link href="/terms">{chunks}</Link>,
})

A tag with no content still needs a closing tag in the message, <br></br>. t.markup does the same with strings, and t.raw returns the message unparsed.

Dates, numbers, lists and relative time

tsxtsx
import { useFormatter, useNow } from 'next-intl'
export function OrderMeta({ placed, total }: { placed: Date; total: number }) {
const format = useFormatter()
const now = useNow()
return (
<p>
{format.number(total, { style: 'currency', currency: 'EUR' })}
{format.dateTime(placed, { dateStyle: 'medium' })}
{format.relativeTime(placed, now)}
{format.list(['HTML', 'CSS', 'JavaScript'], { type: 'conjunction' })}
</p>
)
}
CallEnglishRussian
format.number(1234.5, ...)€1,234.501 234,50 €
format.dateTime(date, ...)Nov 23, 202623 нояб. 2026 г.
format.relativeTime(twoDaysAgo, now)2 days ago2 дня назад
format.list([...])HTML, CSS, and JavaScriptHTML, CSS и JavaScript

The same formatting works inside a message: {date, date, medium}, {value, number, percent}, or a skeleton that starts with ::, such as {date, date, ::yyyyMMMd}. Named formats can be defined once under formats in the request config and reused by name.

A currency code in a message, as in ::currency/EUR, is part of the syntax. It formats the amount for the locale and does not convert it. A translator, human or model, must not change it to the local currency.
Watch out

Part 6: navigation, localized pathnames and the language switcher

Link from src/i18n/navigation.ts adds the prefix for you. <Link href="/about"> points to /de/about on a German page, and <Link href="/" locale="de"> switches language and sets hreflang on the anchor.

Localized pathnames

To translate the URL itself, map internal paths to external ones:

tsts
export const routing = defineRouting({
locales: ['en', 'de'],
defaultLocale: 'en',
pathnames: {
'/': '/',
'/about': { de: '/über-uns' },
'/news/[articleSlug]': { de: '/neuigkeiten/[articleSlug]' },
},
})

/de/über-uns is served by app/[locale]/about/page.tsx. Links then use the internal path, with parameters as an object: href={{ pathname: '/news/[articleSlug]', params: { articleSlug: 'launch' } }}. Localized pathnames need the proxy, so they are not available with a static export.

A switcher that keeps the current page

src/components/LocaleSwitcher.tsxtsx
'use client'
import { useLocale } from 'next-intl'
import { usePathname, useRouter } from '@/i18n/navigation'
import { routing } from '@/i18n/routing'
export function LocaleSwitcher() {
const locale = useLocale()
const pathname = usePathname()
const router = useRouter()
return (
<select
value={locale}
onChange={(event) =>
router.replace(pathname, { locale: event.target.value })
}
>
{routing.locales.map((code) => (
<option key={code} value={code}>
{code}
</option>
))}
</select>
)
}

usePathname here returns the path without the locale prefix, so replacing it under another locale lands on the same page. With pathnames configured, pass { pathname, params } with the result of useParams() so dynamic segments are kept.


Part 7: type-safe message keys

One declaration file turns the source messages into types:

global.tsts
import { routing } from '@/i18n/routing'
import messages from './messages/en.json'
declare module 'next-intl' {
interface AppConfig {
Locale: (typeof routing.locales)[number]
Messages: typeof messages
}
}

t('descriptoin') is now a compile error, and useLocale() returns 'en' | 'de' | 'ar'. Run tsc --noEmit in CI and a renamed key cannot ship half-updated.

Arguments can be typed too, so t('greeting') without name fails. That needs allowArbitraryExtensions in tsconfig.json and the plugin's experimental.createMessagesDeclaration option pointed at ./messages/en.json, which generates messages/en.d.json.ts.


Part 8: metadata and SEO

Title and description per locale

src/app/[locale]/layout.tsxtsx
import type { Metadata } from 'next'
import { getLocale, getTranslations } from 'next-intl/server'
const OG_LOCALE: Record<string, string> = {
en: 'en_US',
de: 'de_DE',
ar: 'ar_EG',
}
export async function generateMetadata(): Promise<Metadata> {
const locale = await getLocale()
const t = await getTranslations('Metadata')
return {
metadataBase: new URL('https://example.com'),
title: t('title'),
description: t('description'),
openGraph: { locale: OG_LOCALE[locale] },
}
}

openGraph.locale renders <meta property="og:locale">. The map is yours to define, and the Next.js example uses the en_US form.

`hreflang`

Google's documentation sets the rules. Each language version lists itself and every other version, URLs are fully qualified, and an x-default entry names the page for visitors who match no language. The annotations can go in <link> tags, HTTP headers or the sitemap. Google calls the three equivalent and suggests choosing one.

With next-intl you already have one. The proxy sends a link response header with an entry per locale plus x-default. If your pages do not exist in every language, or a CMS owns the slugs, set alternateLinks: false in the routing config and declare them yourself:

src/app/[locale]/pricing/page.tsxtsx
import type { Metadata } from 'next'
import { getLocale } from 'next-intl/server'
import { getPathname } from '@/i18n/navigation'
import { routing } from '@/i18n/routing'
export async function generateMetadata(): Promise<Metadata> {
const locale = await getLocale()
const languages: Record<string, string> = {}
for (const code of routing.locales) {
languages[code] = await getPathname({ locale: code, href: '/pricing' })
}
return {
alternates: {
canonical: await getPathname({ locale, href: '/pricing' }),
languages: { ...languages, 'x-default': languages.en },
},
}
}

Next.js renders alternates.languages as <link rel="alternate" hreflang="..."> tags and resolves relative paths against metadataBase. A relative path without metadataBase is a build error.

alternates set in a layout is inherited unchanged by every page below it, so every page would claim the home page as its translation. Set it per page.
Watch out

`lang`, `dir` and what Google reads

Google states that it does not use the lang attribute or hreflang to detect a page's language. It reads the visible content. Set lang and dir anyway: screen readers use lang, and browsers use dir.

The same documentation recommends a separate URL per language over cookies or browser settings, and advises against redirecting visitors by guessed language, because it can keep users and crawlers from other versions. The setup here follows that. Prefixed URLs never redirect, and only the unprefixed root negotiates.

Localized sitemap

src/app/sitemap.tsts
import type { MetadataRoute } from 'next'
import { getPathname } from '@/i18n/navigation'
import { routing } from '@/i18n/routing'
const host = 'https://example.com'
const pages = ['/', '/pricing'] as const
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const entries: MetadataRoute.Sitemap = []
for (const href of pages) {
const languages: Record<string, string> = {}
for (const locale of routing.locales) {
languages[locale] = host + (await getPathname({ locale, href }))
}
for (const locale of routing.locales) {
entries.push({
url: languages[locale],
lastModified: new Date(),
alternates: { languages },
})
}
}
return entries
}

Sitemap alternates has been supported since Next.js 14.2 and is written as xhtml:link elements. The file lives outside [locale], so the proxy matcher must skip sitemap.xml. The next-intl matcher does, because it ignores paths that contain a dot.


Part 9: right to left and fonts

Right to left

The layout in Part 3 sets dir="rtl" for Arabic, Hebrew, Persian and Urdu. MDN recommends setting dir on the root element and preferring the attribute over the CSS direction property, because direction belongs to the content. lang does not imply a direction.

CSS written with physical sides will not follow. Use logical properties:

PhysicalLogical
margin-leftmargin-inline-start
padding-rightpadding-inline-end
left: 0inset-inline-start: 0

Icons that point somewhere, such as back arrows, need mirroring by hand. Put one right to left language in the first batch.

Fonts with `next/font`

next/font/google downloads font files at build time and self-hosts them. The subsets option names the subsets to preload, and a font used in a layout is preloaded on every route under that layout. With a single locale layout, an Arabic font would be preloaded on English pages too. Turn preloading off for script-specific fonts and apply them by locale:

tsxtsx
import { Inter, Noto_Sans_Arabic } from 'next/font/google'
const inter = Inter({ subsets: ['latin'], variable: '--font-latin' })
const arabic = Noto_Sans_Arabic({
subsets: ['arabic'],
variable: '--font-arabic',
preload: false,
})
// in the layout: <html className={`${inter.variable} ${arabic.variable}`}>
csscss
html { font-family: var(--font-latin), sans-serif; }
html[lang='ar'] { font-family: var(--font-arabic), sans-serif; }

Subset names are listed on each font's Google Fonts page. The Google Fonts stylesheet for Noto Sans Arabic lists arabic, latin and latin-ext among its subsets. Check that your brand font covers Cyrillic or Greek before launch, or those characters fall back to a system font.


Part 10: caching and CDN considerations

  • The URL is the cache key. With a prefix per locale and generateStaticParams, each language is a separate static page that any CDN can cache without extra rules.
  • Only the unprefixed root varies. The redirect from / depends on Accept-Language and a cookie. If a shared cache in front of your app stores that response, it has to key on both. The standard way to declare the header part is Vary: Accept-Language. The simpler choice is not to cache the redirect.
  • localePrefix: 'never' gives up URL-based caching. The same URL serves every language, chosen by cookie or header.
  • Reading a cookie in the request config makes pages dynamic. next-intl's setup without locale routing reads cookies() there, which suits an app behind a login and does not suit a marketing site.
  • Forwarded host. next-intl builds the hreflang header from x-forwarded-host, falling back to host. Behind your own proxy or CDN, make sure that header is set and that a client cannot overwrite it.
  • Build time grows with locales. Pages multiplied by locales are rendered at build. Return fewer locales from generateStaticParams and the rest render on first visit.
  • Messages are payload. Messages used only in Server Components never reach the browser. Messages given to NextIntlClientProvider do.

Part 11: the Pages Router `i18n` config

Older apps on the Pages Router use a different, built-in mechanism:

next.config.js, Pages Routerjs
module.exports = {
i18n: {
locales: ['en', 'de', 'ar'],
defaultLocale: 'en',
},
}
Pages Router i18nApp Router
RoutingAutomatic. pages/blog.js is served at /blog and /de/blogA [locale] folder you create
Default localeNo prefixYour choice
DetectionBuilt in on /, from Accept-Language. localeDetection: false turns it offWritten in proxy.ts, or by a library
Remembered choiceNEXT_LOCALE cookie, which overrides the headerSame cookie name in next-intl
Reading the localeuseRouter().locale, and the locale in getStaticProps contextparams, or next/root-params
lang attributeAdded automaticallySet in the root layout
hreflangAdded by hand with next/headalternates.languages, or the next-intl header
Limits100 locales. Does not work with output: 'export'None documented

The config handles routing only. Translations still need a library, and next-intl supports the Pages Router by wrapping _app.tsx in NextIntlClientProvider with locale={router.locale} and loading messages in getStaticProps. The App Router guide does not use the i18n option, so a migration means moving pages under [locale] and adding a proxy.


Part 12: tests, lint and CI

Unit tests with a provider

src/components/CartSummary.test.tsxtsx
import { render } from '@testing-library/react'
import { NextIntlClientProvider } from 'next-intl'
import { expect, it } from 'vitest'
import messages from '../../messages/ru.json'
import CartSummary from './CartSummary'
it.each([
[1, '1 товар в корзине'],
[3, '3 товара в корзине'],
[5, '5 товаров в корзине'],
[21, '21 товар в корзине'],
])('uses the right plural form for %i', (count, text) => {
const { container } = render(
<NextIntlClientProvider locale="ru" messages={messages}>
<CartSummary count={count} />
</NextIntlClientProvider>
)
expect(container.textContent).toBe(text)
})

Write components that translate as non-async functions where you can. They render in a test without mocking the server. If a test imports from createNavigation, the documentation asks for server.deps.inline: ['next-intl'] in the Vitest config. Test the plural boundaries of the language with the most forms you ship.

Playwright per locale

Playwright's locale option sets navigator.language and the Accept-Language header, which is exactly what the proxy reads.

e2e/locale.spec.tsts
import { expect, test } from '@playwright/test'
test.use({ locale: 'de-DE' })
test('a German browser lands on /de', async ({ page }) => {
await page.goto('http://localhost:3000/')
await expect(page).toHaveURL(/\/de$/)
await expect(page.locator('html')).toHaveAttribute('lang', 'de')
})

Add one test with ar-EG that asserts dir="rtl".

Missing keys in CI

Three checks cover different failures:

  • tsc --noEmit with the declaration from Part 7 catches a key used in code that the source file lacks.
  • A message linter compares the locale files. The next-intl documentation points to @eloqnt/cli, whose eloqnt lint command reports rules such as missing-translation and inconsistent-args.
  • The script in Part 13 checks ICU structure with no service involved.
.github/workflows/i18n.ymlyaml
name: i18n
on: [pull_request]
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: 22
cache: npm
- run: npm ci
- run: npx tsc --noEmit
- run: node scripts/check-messages.mjs
- run: npx vitest run
- run: npm run build

If translation happens after merge, move the missing-key check to the release workflow so feature branches are not blocked. Localization as code covers that trade, and React localization CI checks goes deeper on the lint side.


Part 13: translating ICU messages with AI, and checking them

A model translates interface text well enough to draft every language in one run. ICU messages are where drafts break, because the value mixes prose with syntax.

What breaksExampleEffect in next-intl
An argument name is translated{name} becomes {имя}Formatting error. The key path is rendered in place of the text
The English plural shape is copiedone and other only, in RussianNo error. 3 printed "3 товаров" where Russian needs "3 товара"
A keyword is translatedplural or other in the target languageInvalid message. The key path is rendered
A category name is translatedone becomes jedenNo error. The branch never matches and other is used
A select branch name is translatedfemale becomes kobietaNo error. The value from code matches nothing and falls to other
An exact case is dropped=0 {Your cart is empty} removed"0 items" where the design had an empty state
A tag is renamed or dropped<link> becomes <b>, or disappearsRenamed: formatting error. Dropped: plain text with no link and no error
A brace is lostA missing }Invalid message. The key path is rendered
A skeleton is edited::currency/EUR becomes ::currency/PLNNo error. Same number, wrong currency
An apostrophe lands before a braceBienvenue sur l'{name}ICU uses single quotes to escape braces. It printed "Bienvenue sur l{name}"
A key is translated"greeting" becomes "powitanie"The original key is missing

Every row except the last was reproduced for this guide with next-intl's core. The rows marked "no error" are the ones to worry about, because nothing fails. How to translate JSON i18n files with AI covers the general case. For ICU, parse both sides and compare structure:

scripts/check-messages.mjs, Node.js 22, needs @formatjs/icu-messageformat-parserjs
import { readdirSync, readFileSync } from 'node:fs'
import { basename, join } from 'node:path'
import { parse, TYPE } from '@formatjs/icu-messageformat-parser'
const dir = 'messages'
const source = 'en'
const flatten = (node, prefix = '', out = {}) => {
for (const [key, value] of Object.entries(node)) {
const path = prefix ? `${prefix}.${key}` : key
if (typeof value === 'string') out[path] = value
else flatten(value, path, out)
}
return out
}
const read = (locale) =>
flatten(JSON.parse(readFileSync(join(dir, `${locale}.json`), 'utf8')))
// Walk the parsed message and collect what must survive translation.
function shape(message) {
const args = new Set()
const tags = new Set()
const selects = {}
const plurals = {}
const walk = (elements) => {
for (const el of elements) {
if (el.type === TYPE.literal || el.type === TYPE.pound) continue
if (el.type === TYPE.tag) {
tags.add(el.value)
walk(el.children)
continue
}
args.add(`${el.value}:${el.type}`)
if (el.type === TYPE.select || el.type === TYPE.plural) {
const target = el.type === TYPE.select ? selects : plurals
target[el.value] = Object.keys(el.options)
for (const option of Object.values(el.options)) walk(option.value)
}
}
}
walk(parse(message))
return { args, tags, selects, plurals }
}
const same = (a, b) => [...a].sort().join() === [...b].sort().join()
const base = read(source)
const problems = []
for (const file of readdirSync(dir).filter((f) => f.endsWith('.json'))) {
const locale = basename(file, '.json')
if (locale === source) continue
const target = read(locale)
const report = (key, text) => problems.push(`${file}: "${key}" ${text}`)
const needed = new Intl.PluralRules(locale).resolvedOptions().pluralCategories
for (const key of Object.keys(target)) {
if (!(key in base)) report(key, 'is not a key in the source file')
}
for (const [key, text] of Object.entries(base)) {
if (target[key] === undefined) {
report(key, 'is missing')
continue
}
let want, got
try {
want = shape(text)
got = shape(target[key])
} catch (error) {
report(key, `is not valid ICU: ${error.message}`)
continue
}
if (!same(want.args, got.args)) report(key, 'arguments differ')
if (!same(want.tags, got.tags)) report(key, 'rich text tags differ')
for (const [name, options] of Object.entries(want.selects)) {
if (got.selects[name] && !same(options, got.selects[name])) {
report(key, `select options for {${name}} differ`)
}
}
for (const [name, options] of Object.entries(got.plurals)) {
const missing = needed.filter((c) => !options.includes(c))
if (missing.length) {
report(key, `plural {${name}} lacks ${missing.join(', ')} for ${locale}`)
}
const exact = (list) => list.filter((o) => o.startsWith('='))
if (!same(exact(want.plurals[name] ?? []), exact(options))) {
report(key, `exact plural cases for {${name}} differ`)
}
}
}
}
problems.forEach((p) => console.error(p))
process.exit(problems.length ? 1 : 0)

Run against a deliberately broken Polish file, it reported the translated argument, the two-form plural that lacked few and many, the dropped =0 case, the renamed tag, the translated select branch, the unclosed brace, the invented key and the missing key. A correct Russian file passed.

It does not compare skeletons such as ::currency/EUR, it does not catch a translated category name in a language that has no use for that category, and it cannot see meaning. A fluent sentence that says the wrong thing passes. Automated localization QA lists what can be checked without a person.

When you prompt a model yourself, send values and write answers back by key. Tell it which plural categories the target language needs, and that argument names, keywords, tag names and select branch names stay exactly as written.
Rule
A cream paper-pulp sieve on a stone plinth with paper strips falling through its slots and one strip with a broken bracket caught on top
Arguments, plural categories, select branches and tags are compared with the source before merge

Doing this with Transglot

Transglot is a continuous localization platform. Glossa, its translation engine, translates the strings that changed, and four quality checks run on every string before it is written: placeholders, plural forms, glossary terms and length. A draft that still fails the placeholder, plural or glossary check after one repair is refused and reported, not written.

There are two ways to use it with Next.js.

The file workflow

next-intl message files are read and written as the format json_nested. From the project root, with Node.js 22 or later:

bashbash
npx transglot@latest init --targets de,ar

init finds the locale files, works out the source language, signs in through the browser, runs the first translation and writes transglot.json:

transglot.jsonjson
{
"url": "https://api.transglot.ai",
"sources": [
{ "path": "messages/{locale}.json", "format": "json_nested", "locales": ["en"] }
],
"pull": [
{ "path": "messages/{locale}.json", "format": "json_nested" }
]
}

After that, transglot push --wait uploads changed strings and waits for the translation, and transglot pull writes the target files. The GitHub Action runs the same round trip on every push to main. Your app keeps next-intl and reads the files as before.

What the documentation says for ICU messages in JSON:

  • An ICU plural is an ordinary string. JSON has no plural construct, so the message is stored as a simple key and written back unchanged. The checks read it according to the project's Message syntax setting. See plural forms.
  • Arguments and tags are checked. Single braces such as {name} and HTML-style tags are among the syntaxes the placeholder check recognizes.
  • Invalid ICU is left out of an export on a project whose message syntax is ICU.
  • Category completeness is documented for plural keys, which JSON cannot carry. Keep scripts/check-messages.mjs in CI for the per-language category check.
  • Untranslated keys are omitted from a pulled file. Merge the default locale's messages in the request config, or expect next-intl to report missing messages.

The runtime SDK: `@transglot/next`

The Next.js runtime package loads a published bundle from the Transglot CDN on the server and seeds a client provider from it, so the first render is translated and text can change without a deploy.

app/[locale]/layout.tsx, as documentedtsx
import { loadTranslations } from '@transglot/next'
import { NextTranslateProvider } from '@transglot/next/client'
import type { ReactNode } from 'react'
export default async function LocaleLayout({
children,
params,
}: {
children: ReactNode
params: Promise<{ locale: string }>
}) {
const { locale } = await params
const snapshot = await loadTranslations({
baseUrl: 'https://api.transglot.ai',
project: 42,
cdnKey: process.env.TRANSGLOT_CDN_KEY!,
locale,
})
return (
<html lang={locale}>
<body>
<NextTranslateProvider key={locale} snapshot={snapshot}>
{children}
</NextTranslateProvider>
</body>
</html>
)
}

Client Components call const { t } = useTranslations() from @transglot/next/client. Server Components build a client with createSeededClient({ snapshots: snapshot }) and call its t.

Its limits, as documented:

  • Next.js 14 or 15. The package page lists those versions with React 18 or 19. It does not list Next.js 16, the version the rest of this guide targets.
  • It is not a next-intl plugin. It has its own provider and its own useTranslations, which returns an object. It does no routing, no locale detection and no hreflang.
  • ICU formatting is not described for it. t(key, params) interpolates values. The package the documentation names for full ICU MessageFormat is @transglot/react-intl, a loader for react-intl.
  • No fallback locale. A missing key returns the key.
  • No automatic refresh. The seeded client does not poll. New publishes arrive when the server calls loadTranslations again, and you control that with a fetchImpl that sets next: { revalidate: 60 }.
  • Keep the CDN key on the server. Passing a loader to the provider sends the key to the browser. It is read-only, and it is visible.
  • Paid plans. Runtime delivery, the CLI, the GitHub Action and the API start on Starter, at $19 a month for 300,000 translated words. The Free plan works in the browser console. Transglot is not self-hostable. See pricing.

An app already built on next-intl fits the file workflow. Other platforms read nested JSON too, and next-intl's documentation shows Crowdin. Test any of them on a four-form plural and a select message first.


Common mistakes

  • Following a middleware.ts tutorial on Next.js 16. The file is proxy.ts and the function is proxy.
  • No matcher on the proxy. Images and static files get redirected to a locale prefix.
  • Trusting match() with any header. Accept-Language: * throws without a fallback.
  • Reading a cookie to choose the language of a page. The page becomes dynamic and the URL stops identifying the language.
  • Importing Link from next/link. Links lose the locale prefix.
  • alternates in a layout. Every page inherits the home page's alternates.
  • Two plural branches in every language. Russian, Polish and Arabic render the wrong word with no error.
  • Preloading every script's font on every page.
  • Expecting the Pages Router i18n option to work in app/.

Checklist

texttext
[ ] Every route lives under app/[locale]
[ ] proxy.ts negotiates Accept-Language and redirects only unprefixed paths
[ ] The proxy matcher skips static files, images, sitemap.xml and robots.txt
[ ] generateStaticParams returns the locales to pre-render
[ ] No cookies() or headers() call decides a page's language
[ ] Messages use ICU, with every plural category the language needs
[ ] Dates, numbers and currency go through the formatter
[ ] A time zone is set in the request config
[ ] Link, useRouter and redirect come from createNavigation
[ ] The language switcher keeps the current path
[ ] AppConfig types the locale and the message keys
[ ] generateMetadata sets title, description and og:locale per locale
[ ] hreflang declared once: header, link tags or sitemap, with x-default
[ ] lang and dir set on <html>, CSS uses logical properties
[ ] Script-specific fonts are not preloaded on other locales
[ ] Unit tests cover plural boundaries, Playwright covers detection
[ ] tsc, check-messages.mjs and the build run in CI
[ ] One right to left language and one four-form language in the first batch

Frequently asked questions

How do I add i18n to a Next.js App Router project?

Move your routes under app/[locale], add a proxy.ts that redirects unprefixed paths to the visitor's language, and load translations on the server. With next-intl that is defineRouting, createMiddleware(routing), a request config and NextIntlClientProvider in the locale layout.

Is it middleware.ts or proxy.ts in Next.js?

In Next.js 16 it is proxy.ts, exporting a function named proxy. middleware.ts is the name used up to Next.js 15 and is deprecated. A codemod, middleware-to-proxy, renames both.

What is next-intl?

next-intl is an internationalization library for Next.js. It provides ICU message formatting, date and number formatting, locale routing through a proxy, locale-aware Link and useRouter, and TypeScript checks on message keys, in Server and Client Components.

Does the App Router support the i18n option in next.config.js?

That option belongs to the Pages Router, where it has provided automatic locale routing and detection since Next.js 10. The App Router internationalization guide uses a [locale] segment and Proxy.

How do I make next-intl pages static?

Return your locales from generateStaticParams in the locale layout. On Next.js 16.3 or later, read the locale from next/root-params in the request config and nothing else is needed. On older versions, call setRequestLocale(locale) in every layout and page.

How do I add hreflang tags in Next.js?

Return alternates.languages from generateMetadata, with metadataBase set, or add alternates.languages to each entry in sitemap.ts. next-intl's proxy also sends the same information as a link response header by default. Use one method.

How do I build a language switcher that stays on the same page?

In a Client Component, read usePathname() and useRouter() from next-intl's createNavigation, then call router.replace(pathname, { locale }). The pathname has no locale prefix, so it resolves to the same page in the new language.

Can AI translate next-intl JSON files?

Yes, with checks. A model can translate argument names, copy the two English plural branches into a language that needs four, or rename a tag. Parse each message and compare its arguments, plural categories, select branches and tags with the source before merging.

How this guide was checked

  • The [locale] segment, locale negotiation, dictionaries, next/root-params, generateStaticParams, proxy.ts, generateMetadata, sitemap.ts, next/font and the Pages Router i18n config follow the Next.js documentation pages listed under Sources, read on the review date. The latest release post on the Next.js blog was 16.4, and npm listed next 16.4.6.
  • The next-intl parts follow the next-intl documentation for version 4, with next-intl 4.16.0 on npm. Code samples follow those pages, adapted to one example app.
  • Run for this guide with Node.js 22: the Accept-Language negotiation with negotiator and @formatjs/intl-localematcher, including the * failure, the English and Russian messages through next-intl's core (use-intl 4.15), the formatter outputs in Part 5, the failures in the Part 13 table except the translated key, and scripts/check-messages.mjs against a correct Russian file and a broken Polish file.
  • Not run: no Next.js app was built. The proxy, layouts, navigation, metadata, sitemap, font, Vitest, Playwright and CI samples were written to the documentation and not executed.
  • The caching notes in Part 10 are reasoning from the documented behavior of static rendering, Proxy and the Vary header. No CDN was tested.
  • next-i18next, Paraglide JS, Lingui and @eloqnt/cli are described from their own documentation and were not installed or benchmarked. No translation platform was benchmarked.
  • Transglot statements follow the Transglot documentation, including the limits listed in that section. @transglot/next was not run.

Sources

colophon

Who wrote this, and what to read next

wrote this

transglot team

The byline on this post has no profile yet. Author profiles are managed alongside the posts themselves.

Engineering
keep reading

How to Translate a React or Next.js App Automatically

The three parts of automatic translation in a React or Next.js app, the tools that cover each part, and a setup that keeps every language current on each push.

November 23, 2026
8 min read
keep reading

How to Translate JSON i18n Files with AI

Three ways to translate a JSON locale file with AI, what breaks when you paste it into a chatbot, and the checks that keep keys, placeholders and plurals intact.

November 23, 2026
8 min read
keep reading

React localization: check keys, variables and plurals

Build a small React localization workflow with i18next. Catch missing keys, renamed variables and plural errors before deployment with a Node.js CI check.

November 9, 2026
10 min read
works with what you already run

41 connectors, already built.

the pipeline this post describes

Try it on your own strings. Free, no card.

Free plan: 100,000 words to start (25,000 at sign-up, 75,000 after a phone check), then 10,000 a month, 15 locales including your source, 3 seats.