Skip to content

Arabic localization in Next.js

Localize a Next.js app into Arabic with consistent routing, server and client messages, plural rules, formatting, metadata and static pages.

By , Founder of Ritla

Guide12 min read

An Arabic heading does not make a Next.js page fully localized. Its filter button may still use an English client catalog, its count may follow English grammar, and its metadata may come from a shared English layout. These failures can coexist on a page whose URL and direction look correct.

Treat locale as an input to rendering, message selection, formatting and metadata. Each Arabic page needs a stable URL and a consistent answer at every layer. Do not let a browser preference, server default or fallback catalog quietly choose a different language halfway through the response.

The example is a fictional engraving-template library. Its public catalogue has Arabic and English versions, downloadable templates, an availability count and interactive filters. The implementation uses the App Router, Next.js 16.3 or later, and next-intl's current root-parameter integration. Earlier projects should follow the library's documented version-specific setup rather than mixing old and new locale APIs.

Establish what an Arabic URL promises#

For this application, /ar/templates means Arabic interface copy and RTL document direction. /en/templates means English and LTR. The path after the locale can stay the same; a localized page does not require translating every URL segment.

Keep content identity separate from translated slugs. A template named differently in Arabic and English should still have one stable record identifier. Language switching and alternate links must find the corresponding record, rather than guess its translation by replacing words in a URL.

Define the supported locales in i18n/routing.js:

js
import { defineRouting } from "next-intl/routing"; export const routing = defineRouting({  locales: ["en", "ar"],  defaultLocale: "en",  localePrefix: "always"});

An explicit Arabic URL takes precedence over entry-page language negotiation. Browser preferences and a locale cookie can help choose a destination when the visitor has not selected one. They should not make an Arabic deep link render English.

The next-intl routing configuration supports prefixed, unprefixed and domain-based strategies. Choose one policy and apply it to links, redirects, metadata and generated pages. Combining incompatible assumptions produces duplicate destinations and language switches that land on a different screen.

Connect routing to request-specific messages#

Install next-intl in the application and connect its plugin in next.config.mjs. Merge this wrapper with the project's existing configuration:

js
import createNextIntlPlugin from "next-intl/plugin"; const withNextIntl = createNextIntlPlugin("./i18n/request.js");export default withNextIntl({});

The plugin documentation describes request-configuration discovery. Using an explicit path makes the file relationship visible here.

In proxy.js, connect the routing configuration:

js
import createMiddleware from "next-intl/middleware";import { routing } from "./i18n/routing.js"; export default createMiddleware(routing); export const config = {  matcher: "/((?!api|trpc|_next|_vercel|.*\\..*).*)"};

This follows the library's documented matcher for application pages. Routes containing dots need an explicit matcher adjustment; do not assume that a filename-shaped content slug reaches this proxy. The convention is proxy.js in Next.js 16, while older examples may use middleware.js.

Create i18n/request.js with a fixed loader map:

js
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.js"; const loadMessages = {  en: () => import("../messages/en.json").then((module) => module.default),  ar: () => import("../messages/ar.json").then((module) => module.default)}; export default getRequestConfig(async ({ locale }) => {  const selected = locale ?? await rootParams.locale();  if (!hasLocale(routing.locales, selected)) notFound();   return {    locale: selected,    messages: await loadMessages[selected](),    timeZone: "Asia/Amman"  };});

The explicit locale passed by an API such as getTranslations({locale}) is validated too. No arbitrary route segment becomes an import path. Request configuration keeps one visitor's locale separate from another's; do not implement this with a mutable module-level current-language variable. The request configuration reference explains that scope.

The current routing setup uses next/root-params, available by default from Next.js 16.3. Its older requestLocale and setRequestLocale approach has different static-rendering requirements. Pick the setup matching the installed versions.

Declare document language and direction on the server#

Place the root layout at app/[locale]/layout.jsx, with no parent app/layout.jsx rendering another document. This gives the root access to the locale segment. Validate it before using it:

jsx
import { notFound } from "next/navigation";import { hasLocale, NextIntlClientProvider } from "next-intl";import { getMessages } from "next-intl/server";import { routing } from "../../i18n/routing.js"; export const metadata = {  metadataBase: new URL("https://engraving.example")}; export default async function LocaleLayout({ children, params }) {  const { locale } = await params;  if (!hasLocale(routing.locales, locale)) notFound();  const messages = await getMessages();   return (    <html lang={locale} dir={locale === "ar" ? "rtl" : "ltr"}>      <body>        <NextIntlClientProvider locale={locale}          messages={{ TemplateControls: messages.TemplateControls }}>          {children}        </NextIntlClientProvider>      </body>    </html>  );}

Replace the reserved example origin with the deployment's public origin. This provider intentionally sends only the interactive controls' namespace to the client. Server Components can still read the request's complete messages.

Language and direction do different jobs: lang="ar" identifies Arabic, while dir="rtl" establishes base direction. W3C's HTML direction guidance explains why neither substitutes for the other. A post-mount document mutation leaves the initial response inconsistent and can conceal a server-resolution failure.

If the product adds regional Arabic locales, extend the configuration explicitly. The binary direction expression here is valid because the supported registry contains only English and Arabic.

Translate complete messages, including Arabic plural forms#

Problem: an English-style singular/plural branch chooses one noun for a count of one and another for everything else. Translating those two strings leaves Arabic grammar incomplete. Concatenating a formatted number with a translated noun also prevents the translator from changing the sentence structure.

Better: give the translator a complete availability message with Arabic's cardinal categories. Put this in messages/ar.json:

json
{  "Templates": {    "title": "قوالب النقش",    "description": "تصفح قوالب النقش وملفاتها وتعليمات استخدامها.",    "available": "{count, plural, zero {لا توجد قوالب متاحة.} one {يوجد قالب واحد متاح.} two {يوجد قالبان متاحان.} few {توجد {countText} قوالب متاحة.} many {يوجد {countText} قالباً متاحاً.} other {يوجد {countText} قالب متاح.}}"  },  "TemplateControls": {    "vectorOnly": "القوالب المتجهة فقط",    "download": "تنزيل القالب",    "downloadFailed": "تعذر تنزيل القالب. حاول مجدداً."  }}

Use the matching structure in messages/en.json:

json
{  "Templates": {    "title": "Engraving templates",    "description": "Browse engraving templates, files and usage instructions.",    "available": "{count, plural, one {One template is available.} other {{countText} templates are available.}}"  },  "TemplateControls": {    "vectorOnly": "Vector templates only",    "download": "Download template",    "downloadFailed": "The template could not be downloaded. Try again."  }}

These counts are nonnegative integers. The Arabic branches cover zero, one, two, few, many and other; the last category is not synonymous with a large count. Unicode's Arabic plural rules define their selection. Use fixtures for 0, 1, 2, 3, 11 and 100 to reach each category.

The next-intl translation reference documents ICU messages and rich text. Keep count numeric for category selection. The separate countText argument below controls the displayed digits; passing a formatted Arabic string as count confuses data with presentation.

Have an Arabic reviewer check the complete sentences in their product context. Matching JSON keys and covering plural categories cannot establish whether the terminology or grammar fits the actual interface.

Keep an unavailable count separate from a count of zero. While catalogue data is loading, substituting zero would show the translated message claiming that no templates exist. A failed request needs its own translated failure state too. Validate the count before formatting: it must be a finite, nonnegative integer for this message's contract. Do not turn an absent API field into zero merely to avoid an ICU error, or parse a localized display string to recover the count. The message describes a known quantity; pending and failed requests have different meanings in either language.

Keep translations on the server when interactivity does not need them#

An async Server Component can use getTranslations. It does not need to become a Client Component to render a localized count. For example, save this as app/components/TemplateAvailability.jsx:

jsx
import { getTranslations } from "next-intl/server"; export async function TemplateAvailability({ locale, count }) {  const t = await getTranslations({ locale, namespace: "Templates" });  const countText = new Intl.NumberFormat(locale, {    numberingSystem: locale === "ar" ? "arab" : "latn"  }).format(count);   return <p>{t("available", { count, countText })}</p>;}

Its caller supplies a validated locale and the catalogue's integer count from the data layer. This is a component fragment, not a claim that a backend or catalogue page has been implemented. The document inherits its language and direction from the root.

For an interactive filter, either pass a translated label from the server or use useTranslations("TemplateControls") in a Client Component beneath the provider. The root example supplies that namespace. A client component requesting Templates would require that namespace to be supplied as well.

For example, this app/components/VectorFilterToggle.jsx demonstrates a localized toggle and its pressed state. Connecting that setting to the catalogue query is a separate application concern:

jsx
"use client"; import { useState } from "react";import { useTranslations } from "next-intl"; export function VectorFilterToggle() {  const t = useTranslations("TemplateControls");  const [enabled, setEnabled] = useState(false);   return (    <button type="button" aria-pressed={enabled}      onClick={() => setEnabled((previous) => !previous)}>      {t("vectorOnly")}    </button>  );}

The action label remains the same while aria-pressed conveys whether the setting is active. Check the initial server preview, the hydrated button and the button after switching languages. A catalog existing on the server does not prove that this client component received it.

Nested providers need particular attention when selecting messages. next-intl treats the messages prop as an atomic value, rather than deeply merging every namespace with its parent. A nested provider supplying only another namespace can therefore hide TemplateControls from this toggle. Merge the required message objects deliberately or keep the provider boundary narrow. When only one interactive subtree shows missing keys, inspect its nearest provider before concluding that the Arabic catalog failed to load everywhere.

Do not pass the server's translation function through client props. Send serializable labels or use the client provider's supported message configuration. The server/client integration guide describes these alternatives. Avoid promoting an entire catalogue to client rendering solely because one filter has state.

When an action fails, translate the error path as deliberately as the button. A stable error code can be mapped through the current catalog. A translated string returned by an earlier request needs a locale-switch policy so it does not remain in the previous language.

Set formatting policy instead of inheriting the host's defaults#

Problem: calling toLocaleString() without a locale makes output depend on the runtime. A server and a visitor's browser can choose different conventions. A date also depends on calendar and time zone, not just translated month names.

Better: define the catalogue's policy once. This fictional service uses the Gregorian calendar and Amman time for publication dates, with Arabic-Indic digits in Arabic and Western digits in English. A standalone lib/template-formatters.js can provide:

js
export function templateFormatters(locale) {  if (locale !== "ar" && locale !== "en") {    throw new RangeError("Unsupported catalogue locale");  }  const numberingSystem = locale === "ar" ? "arab" : "latn";  const regionalLocale = locale === "ar" ? "ar-JO" : "en-GB";   return {    number: new Intl.NumberFormat(regionalLocale, { numberingSystem }),    published: new Intl.DateTimeFormat(regionalLocale, {      calendar: "gregory", numberingSystem, timeZone: "Asia/Amman",      year: "numeric", month: "long", day: "numeric"    })  };}

Format a publication instant from a full timestamp, such as 2032-11-09T21:40:00Z, rather than parsing a localized display string. Do not treat a date-only business value as an instant unless that matches the data model.

MDN's number-formatting reference and date-formatting reference describe the underlying APIs. next-intl also offers number formatters and date formatters; configure equivalent options if using those APIs.

Keep identifiers separate. A template reference such as 8136-BURIN is not a number to localize. Preserve its source value and isolate it when displaying it in Arabic prose. Formatting a quantity and protecting a fixed-format code are different jobs.

For relative publication times, share the initial reference time between server and client rather than evaluating two unrelated clocks during hydration. Exact formatting can also vary with runtime locale data, so verify the deployed Node and browser environments instead of assuming explicit options freeze every glyph forever.

Keep client navigation consistent with locale routing#

Create locale-aware navigation helpers in i18n/navigation.js:

js
import { createNavigation } from "next-intl/navigation";import { routing } from "./routing.js"; export const { Link, redirect, usePathname, useRouter, getPathname } =  createNavigation(routing);

Components importing this Link can use href="/templates" for the current locale, or an explicit locale="ar" to switch language. These are the library's wrappers, not an assumption that every next/link import has the same locale behavior. The navigation API documents the distinction.

When a template has translated slugs, resolve its corresponding record before switching. Do not send a detail-page visitor to the catalogue root and call that a translation of the same page. Preserve stable filter identifiers where appropriate; decide separately what happens to a free-text search phrase.

Test the switch from English to Arabic, Arabic to English, and browser Back. The URL, document attributes, server messages and client controls should agree after each transition. An isolated provider update with an unchanged URL leaves the server's next request free to return the previous language.

Translate metadata from the same catalog#

The catalogue's Arabic heading and its browser title should not have independent translation ownership. In app/[locale]/templates/page.jsx, add this metadata export alongside the actual page component:

jsx
import { notFound } from "next/navigation";import { hasLocale } from "next-intl";import { getTranslations } from "next-intl/server";import { routing } from "../../../i18n/routing.js"; export async function generateMetadata({ params }) {  const { locale } = await params;  if (!hasLocale(routing.locales, locale)) notFound();  const t = await getTranslations({ locale, namespace: "Templates" });  const title = t("title");  const description = t("description");   return {    title, description,    alternates: {      canonical: `/${locale}/templates`,      languages: { en: "/en/templates", ar: "/ar/templates" }    },    openGraph: {      title, description, locale: locale === "ar" ? "ar_JO" : "en_GB"    },    twitter: { card: "summary", title, description }  };}

The explicit locale makes the metadata request independent of a browser-side provider. The root's metadataBase resolves the paths. The Open Graph locale uses an explicit regional value for this example; it is not the same syntax as the document language tag.

next-intl documents translation outside components, while the Next.js Metadata API defines these fields. Detail pages must produce record-specific canonical and alternate URLs instead of inheriting catalogue paths.

Only advertise an Arabic counterpart that exists and is published. Do not canonicalize every Arabic page to English just because English supplied the source translation. Inspect inherited metadata, image descriptions and sharing text too: translating the title alone leaves other public surfaces in English.

Generate pages for published locale variants#

Add this export to the locale root layout when its supported locale paths should be generated:

js
export function generateStaticParams() {  return [{ locale: "en" }, { locale: "ar" }];}

The root-parameter integration used here supports static rendering without adding the older setRequestLocale pattern. Request-dependent work elsewhere can still affect a route's rendering strategy. Enumerating two locale segments does not prove that every template detail page exists in both languages.

For detail routes, generate published locale-and-slug combinations from the content source. If one template has no published Arabic variant, apply an explicit policy: omit it, show a clearly identified language fallback, or provide a translated unavailable state. Do not silently publish English content under an Arabic URL while advertising it as a finished translation.

Next.js documents generateStaticParams for layouts and pages. Confirm the intended paths in a production build. A development server successfully rendering an Arabic URL on demand is different evidence from a generated deployment containing that route.

When new translations are published, the release process must make their routes discoverable and refresh affected content and metadata. A message catalog update alone does not necessarily generate a previously absent translated content record.

Separate message fallbacks from content fallbacks#

A missing UI message and a missing Arabic template description require different responses. A catalog fallback can keep a control usable, but it also exposes untranslated interface copy. A content fallback may display a creator's original English description intentionally, which should be identified with the appropriate language and direction.

Do not count a fallback value as proof that the Arabic translation exists. Compare message keys and required arguments across catalogs, then inspect the messages actually selected in Arabic. A key can exist while its value remains English or its placeholder is missing.

For rich messages, preserve the value boundary as well as the placeholder. A template code interpolated into a sentence needs isolation around that value; translating its neighboring words does not supply it. Use next-intl's rich-text API when the message contains React nodes. Avoid splitting the sentence into fragments to insert a component manually. Arabic and English mixed text explains the display boundary.

Keep human review focused on terms and meaning, while automated catalog checks catch missing keys, malformed ICU syntax and missing required placeholders. Neither can replace the other. A complete source-language catalog says nothing about whether the Arabic action means the same thing.

Compile every ICU message during the release checks, including branches that the default fixture never renders. Compare required arguments as well as key names: a translated availability message can exist while expecting an argument the component never passes. For rich messages, also check the named tags that the renderer supplies. Allow translators to move those tags within the complete sentence, while requiring the value they protect to remain inside its intended boundary.

Keep localized content isolated in caches and updates#

A cached template description depends on locale and record identity. Include those inputs in application caches and content loaders. A custom cache keyed only by template ID can return an English description after the English page warmed the entry.

Next.js cache behavior depends on the APIs and configuration in use. With Cache Components enabled, use cache includes serializable arguments in its key. Pass locale explicitly when it affects the result. Do not turn off all caching as a substitute for correcting a missing input.

Invalidate the appropriate translated variants when content changes, including metadata derived from them. Test English-first and Arabic-first requests against the same deployed build. Also test a slow response from the old locale arriving after a language switch; it must not overwrite the newer locale's content.

Server-rendered initial labels and client labels must use the same locale and initial values. Browser locale detection after hydration should not replace a locale already chosen by the URL. Preserve drafts and selections according to the product's navigation policy rather than remounting unrelated state to force translations to refresh.

Review the Arabic surfaces that a happy-path page misses#

Inventory the template journey by state: the catalogue, active filters, no results, a missing template, download progress and download failure. Include attribute text such as aria-label, title, placeholders and meaningful image alternatives. Translating visible headings does not cover those strings.

Verify the actual Arabic font used for labels and body text, including controls styled by a component library. Font loading and line height still matter after translation. Allow Arabic labels and error messages to wrap; avoid hiding longer translations in a fixed-height box. Use Arabic text overflow guidance when the translated interface starts clipping.

Review loading and error boundaries, including responses that replace the normal root layout. Their document language, direction and translated recovery actions need explicit ownership. A successful catalogue response does not establish what a server error or unknown route returns.

Before release, open a direct Arabic URL and inspect its initial document, then repeat through the real language switcher. Exercise every Arabic plural category, check a date near the configured time zone's day boundary, and verify the narrow layout with the final font. Inspect the generated title, description and alternate URLs for that exact page.

A free Ritla scan can report <title> or meta description majority-Latin on an Arabic page R004, and a hreflang alternate set that lacks any Arabic entry on an Arabic page R003. For the next release review, use Arabic localization testing and why translation QA is not enough to examine what happens beyond the catalog files.

Checks in this guide

See what your Arabic pages are hiding

Paste a URL. Ritla renders the page on desktop and mobile, runs every check, and shows the top issues with screenshot evidence.

Scan a page freeBrowse the checks