web-i18n — Internationalization for Next.js
1. When to Internationalize (and the cost of doing it late)
Internationalization is architectural. Adding it after launch means touching every component, every route, every metadata block, and every database string field. The longer you wait, the more expensive the retrofit.
Add i18n from day one if any of these are true:
- The product will serve users in more than one language
- The target market includes Arabic, Hebrew, Persian, or Urdu speakers (RTL)
- You need region-specific formatting for dates, currencies, or numbers
- SEO matters across language markets
What you are actually building when you internationalize:
- A routing layer that maps
/en/..., /ar/..., /fr/... to the same pages - A translation pipeline that maps message keys to locale-specific strings
- A formatting layer that uses
Intl.* APIs for dates, numbers, and plurals - An HTML
dir attribute system for RTL languages - A set of SEO
hreflang tags so search engines index the right locale
The cost of doing it late: you will rename every route, audit every hardcoded string, restructure your app/ directory, and patch every <head> block. Plan for a week of pure migration work on a medium-sized app.
2. next-intl Setup (App Router, middleware, routing, messages folder)
Installation
bash
npm install next-intl
Project structure
app/
[locale]/
layout.tsx
page.tsx
about/
page.tsx
messages/
en.json
ar.json
fr.json
es.json
middleware.ts
i18n.ts
next.config.ts
next.config.ts
ts
import createNextIntlPlugin from 'next-intl/plugin'
const withNextIntl = createNextIntlPlugin('./i18n.ts')
const nextConfig = {
// your other config
}
export default withNextIntl(nextConfig)
i18n.ts — request configuration
ts
import { getRequestConfig } from 'next-intl/server'
import { routing } from './middleware'
export default getRequestConfig(async ({ requestLocale }) => {
let locale = await requestLocale
if (!locale || !routing.locales.includes(locale as 'en' | 'ar' | 'fr' | 'es')) {
locale = routing.defaultLocale
}
return {
locale,
messages: (await import(`./messages/${locale}.json`)).default
}
})
middleware.ts
ts
import createMiddleware from 'next-intl/middleware'
export const routing = createMiddleware({
locales: ['en', 'ar', 'fr', 'es'],
defaultLocale: 'en',
localePrefix: 'always'
})
export const config = {
matcher: [
'/((?!api|_next/static|_next/image|favicon.ico|.*\\..*).*)'
]
}
app/[locale]/layout.tsx
tsx
import { NextIntlClientProvider } from 'next-intl'
import { getMessages, getLocale } from 'next-intl/server'
import { notFound } from 'next/navigation'
const locales = ['en', 'ar', 'fr', 'es']
export default async function LocaleLayout({
children,
params
}: {
children: React.ReactNode
params: Promise<{ locale: string }>
}) {
const { locale } = await params
if (!locales.includes(locale)) {
notFound()
}
const messages = await getMessages()
const isRTL = ['ar', 'he', 'fa', 'ur'].includes(locale)
return (
<html lang={locale} dir={isRTL ? 'rtl' : 'ltr'}>
<body>
<NextIntlClientProvider messages={messages}>
{children}
</NextIntlClientProvider>
</body>
</html>
)
}
3. Translation Files Structure (JSON format, nested keys, namespacing)
Design principles
- Namespace by feature or page, not by component
- Keep keys flat within a namespace — avoid nesting deeper than two levels
- Use descriptive keys, not positional ones (
hero.title not hero.text1) - Include context comments in a parallel
_comments file for translators
messages/en.json
json
{
"common": {
"loading": "Loading…",
"error": "Something went wrong",
"retry": "Try again",
"cancel": "Cancel",
"save": "Save",
"delete": "Delete",
"confirm": "Confirm",
"back": "Back",
"next": "Next",
"close": "Close"
},
"navigation": {
"home": "Home",
"about": "About",
"pricing": "Pricing",
"blog": "Blog",
"contact": "Contact",
"signIn": "Sign in",
"signOut": "Sign out",
"dashboard": "Dashboard"
},
"auth": {
"signIn": {
"title": "Sign in to your account",
"emailLabel": "Email address",
"passwordLabel": "Password",
"submit": "Sign in",
"forgotPassword": "Forgot your password?",
"noAccount": "Don't have an account?",
"createAccount": "Create one"
},
"errors": {
"invalidCredentials": "Invalid email or password",
"tooManyAttempts": "Too many attempts. Try again in {minutes} minutes.",
"sessionExpired": "Your session has expired. Please sign in again."
}
},
"dashboard": {
"welcome": "Welcome back, {name}",
"stats": {
"totalOrders": "Total orders",
"revenue": "Revenue",
"activeUsers": "Active users",
"conversion": "Conversion rate"
}
},
"products": {
"itemCount": "{count, plural, =0 {No items} one {# item} other {# items}}",
"addToCart": "Add to cart",
"outOfStock": "Out of stock",
"price": "{price, number, currency}"
},
"errors": {
"notFound": {
"title": "Page not found",
"description": "The page you are looking for does not exist.",
"action": "Go home"
},
"serverError": {
"title": "Server error",
"description": "We are working on fixing this. Please try again shortly."
}
}
}
messages/ar.json
json
{
"common": {
"loading": "جارٍ التحميل…",
"error": "حدث خطأ ما",
"retry": "حاول مرة أخرى",
"cancel": "إلغاء",
"save": "حفظ",
"delete": "حذف",
"confirm": "تأكيد",
"back": "رجوع",
"next": "التالي",
"close": "إغلاق"
},
"navigation": {
"home": "الرئيسية",
"about": "عن الشركة",
"pricing": "الأسعار",
"blog": "المدونة",
"contact": "تواصل معنا",
"signIn": "تسجيل الدخول",
"signOut": "تسجيل الخروج",
"dashboard": "لوحة التحكم"
},
"products": {
"itemCount": "{count, plural, =0 {لا توجد عناصر} one {عنصر واحد} two {عنصران} few {# عناصر} many {# عنصرًا} other {# عنصر}}",
"addToCart": "أضف إلى السلة",
"outOfStock": "نفد المخزون",
"price": "{price, number, currency}"
}
}
Key naming conventions
// Page-scoped
"home.hero.title" → Home > Hero section > title
"home.hero.subtitle" → Home > Hero section > subtitle
"home.cta.primary" → Home > CTA > primary button
// Feature-scoped
"auth.signIn.title"
"auth.signUp.title"
"auth.resetPassword.title"
// Shared
"common.loading"
"common.error"
"errors.notFound.title"
4. useTranslations in Client and Server Components
Server Component (default — preferred)
tsx
// app/[locale]/page.tsx
import { useTranslations } from 'next-intl'
export default function HomePage() {
const t = useTranslations('home')
return (
<main>
<h1>{t('hero.title')}</h1>
<p>{t('hero.subtitle')}</p>
<a href="/pricing">{t('cta.primary')}</a>
</main>
)
}
Server Component with dynamic values
tsx
// app/[locale]/dashboard/page.tsx
import { useTranslations } from 'next-intl'
import { getCurrentUser } from '@/lib/auth'
export default async function DashboardPage() {
const t = useTranslations('dashboard')
const user = await getCurrentUser()
return (
<div>
<h1>{t('welcome', { name: user.firstName })}</h1>
</div>
)
}
Client Component — must receive translations as props or use hook inside provider
tsx
'use client'
import { useTranslations } from 'next-intl'
interface CartButtonProps {
productId: string
disabled?: boolean
}
export function CartButton({ productId, disabled }: CartButtonProps) {
const t = useTranslations('products')
return (
<button
disabled={disabled}
onClick={() => addToCart(productId)}
aria-label={t('addToCart')}
>
{disabled ? t('outOfStock') : t('addToCart')}
</button>
)
}
Server Component with getTranslations (async)
tsx
// Use when you need translations outside a component render
import { getTranslations } from 'next-intl/server'
export async function generateMetadata({
params
}: {
params: Promise<{ locale: string }>
}) {
const { locale } = await params
const t = await getTranslations({ locale, namespace: 'home' })
return {
title: t('meta.title'),
description: t('meta.description')
}
}
Accessing multiple namespaces
tsx
import { useTranslations } from 'next-intl'
export default function CheckoutPage() {
const tCommon = useTranslations('common')
const tCheckout = useTranslations('checkout')
const tErrors = useTranslations('errors')
return (
<form>
<h1>{tCheckout('title')}</h1>
<button type="submit">{tCheckout('placeOrder')}</button>
<button type="button">{tCommon('cancel')}</button>
</form>
)
}
5. Locale Routing (locale prefix, domain-based, automatic detection)
Option A: Prefix-based (recommended for most apps)
/en/about
/ar/about
/fr/about
/es/about
ts
// middleware.ts
export const routing = createMiddleware({
locales: ['en', 'ar', 'fr', 'es'],
defaultLocale: 'en',
localePrefix: 'always' // always prefix, including default locale
// localePrefix: 'as-needed' // omit prefix for default locale only
})
Option B: Domain-based routing
en.example.com/about
ar.example.com/about
fr.example.com/about
ts
// middleware.ts
export const routing = createMiddleware({
locales: ['en', 'ar', 'fr'],
defaultLocale: 'en',
domains: [
{
domain: 'en.example.com',
defaultLocale: 'en',
locales: ['en']
},
{
domain: 'ar.example.com',
defaultLocale: 'ar',
locales: ['ar']
},
{
domain: 'fr.example.com',
defaultLocale: 'fr',
locales: ['fr']
}
]
})
Automatic locale detection from browser
next-intl's middleware reads the Accept-Language header automatically. To customize:
ts
// middleware.ts
import createMiddleware from 'next-intl/middleware'
import Negotiator from 'negotiator'
import { match } from '@formatjs/intl-localematcher'
const locales = ['en', 'ar', 'fr', 'es']
const defaultLocale = 'en'
function detectLocale(request: Request): string {
const acceptLanguage = request.headers.get('accept-language') ?? ''
const languages = new Negotiator({
headers: { 'accept-language': acceptLanguage }
}).languages()
try {
return match(languages, locales, defaultLocale)
} catch {
return defaultLocale
}
}
export const routing = createMiddleware({
locales,
defaultLocale,
localeDetection: true // default; reads Accept-Language header
})
Typed navigation with next-intl
ts
// navigation.ts — create typed navigation helpers
import { createNavigation } from 'next-intl/navigation'
export const { Link, redirect, usePathname, useRouter } = createNavigation({
locales: ['en', 'ar', 'fr', 'es'],
defaultLocale: 'en'
})
tsx
// Use typed Link — locale is handled automatically
import { Link } from '@/navigation'
export function Nav() {
return (
<nav>
<Link href="/about">About</Link>
<Link href="/pricing">Pricing</Link>
<Link href={{ pathname: '/products/[id]', params: { id: '42' } }}>
Product
</Link>
</nav>
)
}
6. Pluralization (one/other/zero forms, count-based messages)
next-intl uses ICU message format for pluralization. The Intl.PluralRules API drives the plural category selection per locale automatically.
ICU plural syntax
{count, plural, =0 {zero form} one {singular} other {plural}}
Translation file entries