Next.js App Router and Arabic localization
Structure Arabic App Router routes with server dictionaries, locale layouts, translated slugs, static generation and matching metadata.
By Omran Khleifat, Founder of Ritla
Guide12 min read
An Arabic App Router route can render the right lesson while its shared layout stays English, its language switch points to an English slug that has no Arabic equivalent, and its canonical names a different page. These defects come from treating the locale prefix as decoration instead of part of the route's identity.
Put locale resolution above the pages that need it. Load interface dictionaries on the server, keep translated content variants attached to one record, and derive generated paths and metadata from those same variants. The resulting structure should explain which Arabic pages exist before a browser opens them.
This guide builds that structure for a fictional beekeeping lesson library. It uses ordinary Server Components and awaited route parameters, without requiring an internationalization library. The focus is App Router architecture, rather than a second tutorial on translating every control or mirroring CSS.
Give the locale segment ownership of its document#
Use a locale segment before the lesson routes. The minimal structure is:
app/ [locale]/ layout.jsx lessons/ [slug]/ page.jsxlib/ locales.js dictionaries.js lessons.jsmessages/ en.json ar.jsonHere, app/[locale]/layout.jsx is the root layout. There is no parent app/layout.jsx rendering another document. The App Router supports placing the root layout below a locale segment, as described in the internationalization guide.
Problem: keeping an English root document and adding an Arabic wrapper in the lesson page gives the wrapper ownership of only one subtree. The header, overlays or other siblings may remain outside it. The document still identifies itself differently from its Arabic content.
Moving another html element into a nested layout does not repair that structure. Choose the layout that actually owns the document. Its route parameters include segments down to that layout, so a top-level layout above [locale] cannot simply read a descendant locale from its own params.
Route groups can organize different application areas without adding URL segments. They do not supply a locale value by themselves. If the application has several root layouts, plan their document attributes separately and account for document navigation between them. The layout reference documents these boundaries.
Validate supported locales before selecting files#
Put the supported document settings in lib/locales.js:
export const localeSettings = { en: { lang: "en", dir: "ltr" }, ar: { lang: "ar", dir: "rtl" }}; export function isLocale(value) { return typeof value === "string" && Object.hasOwn(localeSettings, value);}Do not accept every segment as a locale, and do not treat every value other than English as Arabic. A path that accidentally reaches this dynamic segment still needs validation. The examples reject unsupported values with notFound() instead of silently publishing a fallback page under them.
Keep language and direction as explicit settings. lang="ar" identifies Arabic but does not establish RTL direction; dir="rtl" establishes direction but does not translate anything. W3C's HTML direction guidance explains the distinction.
A separate entry-route policy can redirect an unprefixed request to a supported destination. In current Next.js projects that may use Proxy; earlier examples use Middleware. That routing policy should preserve an explicitly selected Arabic URL. It should also exclude assets and API routes that are not localized pages. This guide starts at the localized lesson URLs shown below and does not implement entry-language negotiation.
Keep the dictionary loader on the server#
Use a closed loader map in lib/dictionaries.js:
import "server-only";import { isLocale } from "./locales.js"; const loaders = { en: () => import("../messages/en.json").then((module) => module.default), ar: () => import("../messages/ar.json").then((module) => module.default)}; export async function getDictionary(locale) { if (!isLocale(locale)) throw new RangeError("Unsupported lesson locale"); return loaders[locale]();}The server-only marker prevents importing this module into a Client Component through an accidental dependency chain. The loader is not a browser hook and should not read a mutable global current-language variable.
For this example, messages/ar.json contains:
{ "siteName": "دروس تربية النحل", "saveLesson": "حفظ الدرس", "loadingLesson": "جار تحميل الدرس."}The corresponding messages/en.json is:
{ "siteName": "Beekeeping field lessons", "saveLesson": "Save lesson", "loadingLesson": "Loading lesson."}Keep interface dictionaries separate from lesson content. The navigation and save control change language with the interface; an author's lesson title and summary belong to a specific published content variant. Combining both into one undifferentiated translation object makes it harder to decide whether a missing value should block publication or use a UI fallback.
These dictionaries contain static messages only. Add a message-formatting library when the interface needs plural categories, rich placeholders or contextual selection. A file loader does not implement Arabic grammar, number formatting or bidi isolation.
Render the localized root before client code runs#
The complete root layout at app/[locale]/layout.jsx is small:
import { notFound } from "next/navigation";import { isLocale, localeSettings } from "../../lib/locales.js";import { getDictionary } from "../../lib/dictionaries.js"; export const metadata = { metadataBase: new URL("https://apiary-lessons.example")}; export function generateStaticParams() { return Object.keys(localeSettings).map((locale) => ({ locale }));} export default async function LocaleLayout({ children, params }) { const { locale } = await params; if (!isLocale(locale)) notFound(); const dictionary = await getDictionary(locale); const { lang, dir } = localeSettings[locale]; return ( <html lang={lang} dir={dir}> <body> <header>{dictionary.siteName}</header> {children} </body> </html> );}Replace the reserved example origin with the deployed site's public origin. The header is deliberately just a label; an application navigation component can receive its own translated labels.
The response now declares the selected language and direction before hydration. Do not add a mount effect to correct the document after showing an English default. Likewise, do not initialize a child provider from browser language when the URL has already supplied the locale.
The root's dictionary await also has a timing consequence: its children cannot supply a loading fallback for work the root itself has not completed. Keep shared dictionary loading predictable and distinguish it from slower lesson-content fetching below the layout.
Load an Arabic-capable font through the application's font pipeline and inspect the rendered glyphs. Font choice belongs to the shell too, but it does not replace direction or translation. Keep that concern separate from the route ownership shown here.
Attach translated slugs to one lesson record#
Problem: generating Arabic URLs by replacing /en/ with /ar/ assumes both languages use the same slug. It also invents an Arabic destination when the lesson has no published translation.
Better: model the translations under a stable record ID. For a runnable content fixture, start lib/lessons.js with:
import "server-only";import { isLocale } from "./locales.js"; export const lessons = [ { id: "frame-reading", translations: { en: { slug: "reading-a-hive-frame", title: "Reading a hive frame", description: "A field lesson about observing comb and brood patterns." }, ar: { slug: "قراءة-إطار-الخلية", title: "قراءة إطار الخلية", description: "درس ميداني حول ملاحظة الأقراص الشمعية وأنماط الحضنة." } } }, { id: "swarm-observation", translations: { en: { slug: "observing-a-swarm", title: "Observing a swarm", description: "A field lesson about recording swarm observations." } } }];This fixture contains published variants only. The second lesson intentionally has no Arabic variant. A production CMS query should apply the equivalent publication filter before returning variants used for public routes and alternate links.
The stable ID connects equivalent content. It is not the public slug and does not change when an editor renames a lesson. Enforce slug uniqueness within each locale; the same slug in different locales is a different route address, while duplicate slugs within Arabic would make resolution ambiguous.
Store one consistent slug representation. Encode it when constructing a URL component, rather than persisting a mixture of encoded and unencoded forms. Arabic slugs do not need to be transliterated merely to work in a route.
Resolve page content through one shared function#
Append these helpers to lib/lessons.js:
export function findLesson(locale, slug) { if (!isLocale(locale) || typeof slug !== "string") return null; const record = lessons.find((lesson) => lesson.translations[locale]?.slug === slug ); return record ? { record, translation: record.translations[locale] } : null;} export function publishedSlugs(locale) { if (!isLocale(locale)) return []; return lessons.flatMap((lesson) => { const translation = lesson.translations[locale]; return translation ? [{ slug: translation.slug }] : []; });} export function lessonPath(locale, translation) { return `/${locale}/lessons/${encodeURIComponent(translation.slug)}`;} export function lessonAlternates(record) { return Object.fromEntries(Object.entries(record.translations).map( ([locale, translation]) => [locale, lessonPath(locale, translation)] ));}The path builder encodes a slug as one URL component. MDN documents encodeURIComponent and its treatment of characters with URL syntax meaning. Avoid encoding an already constructed path again.
Use findLesson for the page and metadata. The shared result prevents one path from selecting Arabic content while another falls back to the English record. With CMS data, apply the same locale and publication constraints to both reads.
The minimal app/[locale]/lessons/[slug]/page.jsx is:
import { notFound } from "next/navigation";import { isLocale } from "../../../../lib/locales.js";import { findLesson } from "../../../../lib/lessons.js"; export default async function LessonPage({ params }) { const { locale, slug } = await params; if (!isLocale(locale)) notFound(); const result = findLesson(locale, slug); if (!result) notFound(); return ( <main> <h1>{result.translation.title}</h1> <p>{result.translation.description}</p> </main> );}This renders the fixture's introductory content, not a complete learning platform. No browser-side locale detector or translation provider is needed for that server-rendered title and paragraph.
Do not rely on the root having validated everything first. Page and metadata entry points should validate the inputs they consume. A route tree is not a promise that independent data work runs sequentially through every parent component.
Generate child slugs from each parent locale#
The root layout already generates the supported locale values. Add this import and export to the lesson page file:
import { publishedSlugs } from "../../../../lib/lessons.js"; export function generateStaticParams({ params: { locale } }) { return publishedSlugs(locale);}Next.js executes the child generator for the parent parameter sets. For English, this fixture returns both lesson slugs. For Arabic, it returns only the translated frame-reading lesson. The page's final parameters contain both the parent locale and child slug.
Notice the API difference: a page component awaits its params promise, while the generator's options.params is a synchronous object containing parent parameters. The static parameter reference documents this top-down generation pattern.
Do not generate the Cartesian product of every locale and every English slug. That produces URLs without corresponding content and makes metadata fallback conceal the mistake. Generate addresses from published variants instead.
Decide what should happen for an address not generated at build time. That depends on the deployment and rendering configuration, not just this list. Check the installed version's route-segment configuration, especially when Cache Components is enabled, before copying older dynamicParams or force-static examples.
Also distinguish generating a path from refreshing one. Next.js documents that generateStaticParams is not called again during ISR revalidation. Publishing a new Arabic variant therefore needs a release or supported on-demand path strategy that can actually expose the new URL. Refreshing the existing English page alone does not establish that result.
Derive canonical and alternate URLs from the resolved variant#
Metadata should describe the same lesson variant the page renders. Append this export to the lesson page, reusing its existing notFound, isLocale and findLesson imports, and add the two path-helper imports shown:
import { lessonPath, lessonAlternates } from "../../../../lib/lessons.js"; export async function generateMetadata({ params }) { const { locale, slug } = await params; if (!isLocale(locale)) notFound(); const result = findLesson(locale, slug); if (!result) notFound(); const { record, translation } = result; return { title: translation.title, description: translation.description, alternates: { canonical: lessonPath(locale, translation), languages: lessonAlternates(record) } };}The root's metadataBase makes those relative paths absolute in the generated metadata. The Arabic lesson points canonically to its own Arabic slug. Its alternate set contains the two published variants of the same record. The English-only lesson advertises only its existing English variant.
Next.js documents metadata resolution, including generated fields on Server Components. Google's localized-page guidance explains the relationship between corresponding language variants. Do not send every detail-page alternate to a language homepage.
Carry the same translated content into sharing metadata where the application uses it. A parent layout's English Open Graph description is not translated by a child page's Arabic title. Review the final merged output for each route, including any inherited title template.
Use the same variant map for a language switcher. That keeps its destination aligned with the alternate links. For the English-only lesson, omit an unavailable switch target or show a translated explanation. Do not manufacture an Arabic link just because the application supports Arabic elsewhere.
Treat a translated slug change as a route change#
An editor can rename the Arabic slug without changing the English slug or the stable lesson ID. That is a change to the Arabic public address, not a new lesson. Update the published variant, its generated path, internal links, canonical and alternate URLs together.
Keep an old-slug mapping when the previous address should continue working. Resolve that mapping within the selected locale and redirect to the current published variant of the same record. Do not redirect an old Arabic lesson address to an unrelated English page merely because the old slug no longer matches.
Next.js supports configuration-based redirects for known path changes and permanentRedirect when the destination is resolved during rendering. The redirect guide explains the available layers. Choose one owner for the migration instead of adding conflicting rules in Proxy, route code and the hosting platform.
Check that an old slug does not collide with another lesson's current slug, and that aliases lead directly to the current destination rather than forming chains. The fixture's resolver intentionally contains no alias handling: it establishes current published addresses only. A production migration must add that behavior explicitly.
After a rename, request both the old and new Arabic addresses. Verify the destination lesson identity, document language and canonical at the final page. Repeat the language switch from the unchanged English variant to confirm it now uses the new Arabic address.
Keep client interactivity below the server dictionary boundary#
A save button can be a Client Component while the lesson remains server-rendered. Load the dictionary in a Server Component and pass dictionary.saveLesson as a serializable label. Keep record identity and locale explicit if the action or response depends on them.
Do not import getDictionary into the button or pass the loader function as a prop. That crosses the wrong boundary. Next.js's Server and Client Components guide explains composition and serializable props.
If a larger interactive subtree needs a translation provider, supply the relevant message subset above it. Use the route's validated locale for its initial render. The provider does not need every lesson body, and it should not independently prefer browser language over the URL.
Format numbers and dates with explicit locale settings on either side of the boundary. A translated shell does not stop a browser or server default from producing another language's date. Likewise, isolate a fixed-format reference such as 5682-HIVE when inserting it into Arabic prose; a server-rendered string still participates in browser bidi layout. See mixed Arabic and English text for that separate concern.
Do not assume every special file receives page parameters#
A tempting loading component is Loading({params}) followed by a dictionary lookup. It does not have the page component's parameter contract. Next.js states that loading components accept no parameters.
For translated loading copy, use a supported request-locale integration, a client locale context supplied above the boundary, or an explicit Suspense fallback created where the validated locale and dictionary are already available. Choose a design that actually has the data it uses, rather than reading an assumed prop.
There is a timing limit: a translated fallback cannot appear before the dictionary providing its text is available. A loading file also does not wrap the layout in its own segment. If the locale layout blocks on a slow dictionary service, a loading file beneath it cannot cover that work.
Error boundaries have another contract. An error.jsx file is a Client Component and does not catch errors from its own segment's layout above it. A dictionary failure in that layout may therefore reach a different boundary than a lesson-content failure. The error convention documents the hierarchy.
Missing content and unsupported locales also deserve separate tests. A missing Arabic lesson under a valid Arabic locale can use that locale's shell. A global not-found response or a failure replacing the root may bypass it. The not-found conventions describe these differences. Make the fallback document's language choice explicit instead of assuming the normal layout always survives.
Account for retained layouts and localized caches#
Within a language, shared layouts can be retained while the visitor moves between lessons. Do not store the current lesson title, slug-specific alternates or query-sensitive labels in a layout that assumes it reruns on every navigation. Keep that work at the page or appropriate dynamic segment.
A language switch must navigate to the corresponding localized route. Changing only client messages leaves the URL and server-rendering inputs behind. Inspect the document after the actual switch, not only after a direct refresh, and account for full document navigation when crossing distinct root layouts.
For a CMS-backed implementation, a content result depends on locale, slug or stable record ID, and publication state. Include the relevant inputs in application caches. With Cache Components enabled, use cache keys include serializable arguments; an unrelated custom cache keyed only by lesson ID still needs correction.
Keep UI dictionary fallback separate from content publication. A missing control label may use an explicit fallback policy, but a missing Arabic lesson should not silently become an English public page under an Arabic address. That would make the generated route list, language switcher and metadata describe different publication states.
The in-file fixture gives the build one content snapshot. A CMS can change while a longer build is generating pages. If the generator enumerates one Arabic slug and a later metadata read sees an editor's replacement slug, the build can combine different publication states even when every function is individually locale-aware.
Where the content system supports it, build against a fixed publication revision or an exported manifest of approved variants. Otherwise define and verify how consistency is maintained between path enumeration and page rendering. Record the content revision alongside the deployment so a failed Arabic URL can be compared with the source state used to produce it. This also separates a routing defect from a translation published after that deployment was built.
Verify the generated route set and its documents together#
For this fixture, the expected set is two English lesson URLs and one Arabic lesson URL. Build a route inventory from the published variants, then compare it with the generated output or reachable production routes. Check omissions as well as unexpected addresses.
For every published variant, open its URL directly and verify the initial document language, direction, title and introductory text. Inspect the canonical and follow every alternate to confirm it resolves to the corresponding lesson. On the bilingual record, navigate through the real language switcher and browser Back.
Try an Arabic URL with the English-only lesson's slug. It should follow the application's missing-translation policy, rather than display English while claiming Arabic. Also try an unsupported locale and a nonexistent slug beneath a supported locale. These exercise different validation paths.
Test loading and content-error states through their real boundaries. Use delayed or failed data responses rather than substituting a static screenshot. Then inspect narrow layouts with the deployed Arabic font: the route architecture can be correct while a translated header or control still clips.
A free Ritla scan of a generated Arabic lesson can report a canonical URL pointing at a different-locale variant , or document direction missing, contradicted, or declared only in CSS . Use testing Arabic releases to carry that review across the published route set, including translated lessons added after the first build.