Next.js RTL: the complete guide
Set up Arabic RTL in the Next.js App Router with locale-aware root layouts, server rendering, fonts, metadata and navigation.
By Omran Khleifat, Founder of Ritla
Guide13 min read
An Arabic Next.js page can display translated content while its document still declares English and left-to-right direction. A client effect may correct it after mounting, but the initial HTML, loading state and metadata have already used a different locale contract.
Start with the document that Next.js sends. In the App Router, the root layout owns html and body. Put that layout where it can read the locale, validate the value, and derive language and direction before rendering. Fonts, component styles and translated metadata then follow that same choice.
This guide uses a fictional indoor climbing route catalogue with English and Arabic URLs. The examples cover the App Router and asynchronous route params; they do not use the Pages Router's localization configuration.
Make the URL's locale the rendering contract#
Use /ar/routes for the Arabic catalogue and /en/routes for English. These are application routes in the example, not Ritla guide links. An explicit Arabic URL should produce Arabic regardless of the visitor's previous cookie or browser language. Preferences can help choose an initial destination when the URL has no locale.
Keep three decisions distinct: which URL the visitor reaches, which language the application renders, and which base direction the document declares. A redirect chooses a destination. It does not translate the destination or make its HTML RTL.
Define the supported values in app/lib/locales.js:
export const localeConfig = { en: { lang: "en", dir: "ltr" }, ar: { lang: "ar", dir: "rtl" }}; export function isLocale(value) { return typeof value === "string" && Object.hasOwn(localeConfig, value);}Do not use an arbitrary route segment as a dictionary filename or infer that every non-English value means Arabic. An unsupported locale should follow an explicit rejection or redirect policy. Here, localized routes reject it with notFound().
For a larger product, extend the registry deliberately with regional locales and their formatting settings. Do not infer direction from the first two characters of every possible language tag. The catalogue only supports the two values shown, which keeps routing, dictionary selection and document attributes aligned.
Put the root layout below the locale segment#
Problem: an English root document with an Arabic wrapper inside a child layout leaves the document itself incorrect. The wrapper changes its subtree, but elements outside it still inherit the root's direction.
Adding an effect that assigns document.documentElement.dir after mounting also leaves the server output wrong. Moving another html element into a nested layout creates a different markup problem.
Better: for this application, omit app/layout.jsx and make app/[locale]/layout.jsx the root layout. The relevant structure is:
app/ globals.css lib/ locales.js [locale]/ layout.jsx routes/ page.jsxproxy.jsNext.js explicitly supports a root layout beneath a locale segment in its internationalization guide. If a parent app/layout.jsx remains, the locale layout becomes nested and should not render another document.
Use this root layout:
import { notFound } from "next/navigation";import { Noto_Sans_Arabic } from "next/font/google";import { isLocale, localeConfig } from "../lib/locales.js";import "../globals.css"; const arabic = Noto_Sans_Arabic({ subsets: ["arabic", "latin"], display: "swap"}); export const metadata = { metadataBase: new URL("https://climbs.example")}; export function generateStaticParams() { return Object.keys(localeConfig).map((locale) => ({ locale }));} export default async function LocaleLayout({ children, params }) { const { locale } = await params; if (!isLocale(locale)) notFound(); const { lang, dir } = localeConfig[locale]; return ( <html lang={lang} dir={dir} className={locale === "ar" ? arabic.className : undefined}> <body>{children}</body> </html> );}Replace the reserved example origin with the deployed site's public origin. The font choice is discussed below. Keep the root layout as a Server Component.
Layout parameters include segments down to that layout, not arbitrary child segments. A top-level layout above [locale] cannot simply read that child locale from its own params. The layout API reference documents parameter scope and the required document elements.
generateStaticParams enumerates supported locale segments for generation; it does not translate pages or enumerate every nested content slug. The static parameter API explains how generation works for nested routes. Retain runtime validation wherever a route entry point consumes a locale.
Give unprefixed requests a deliberate destination#
For this catalogue, / sends visitors to the English catalogue. A small proxy.js at the project root implements that policy:
import { NextResponse } from "next/server"; export function proxy(request) { return NextResponse.redirect(new URL("/en/routes", request.url));} export const config = { matcher: "/" };This matcher handles only the entry URL. It does not rewrite Arabic routes, intercept font files or redirect framework assets. Add language negotiation only when the product requires it, and preserve an explicitly localized destination.
Current Next.js documentation calls this convention Proxy; older projects may have middleware.js. Follow the Proxy documentation for your installed version instead of installing both conventions for the same job.
Verify a direct Arabic request separately from the entry redirect. Otherwise a test can pass because it eventually reaches the correct page while hiding an unnecessary redirect, a discarded deep link or a preference that overrides the user's selected language.
Carry the resolved locale into client components#
The server should choose the initial locale and supply the messages or primitive settings that interactive components need. A language selector, filter control or route-saving button can be a Client Component without making the root document client-owned.
Do not independently initialize that component from navigator.language, local storage or a default English state while the server renders Arabic. Even when both sides eventually settle on Arabic, the first client render disagrees with the supplied document.
Next.js renders an initial HTML preview for Client Components too; the "use client" directive does not mean their first visible output is exempt from server consistency. The Server and Client Components guide explains the boundary and the requirement for serializable props.
Pass a validated locale string, direction string and the relevant translated labels. Do not pass a translation function across that boundary or ship an entire server dictionary loader just to label one button. An established internationalization library may provide its own supported server and client integration; use that integration without letting its fallback locale contradict the route.
Keep locale selection out of mutable process-wide state. A module variable changed while rendering one request is not a request boundary. Two visitors asking for different languages must not depend on which request last assigned a global locale.
Treat language switching as route navigation#
Changing a translation provider while leaving /en/routes in the address bar creates two competing sources of truth. Navigate to the corresponding Arabic route and let its rendering contract apply.
For catalogue links, construct the explicit destination, such as href="/ar/routes". Next.js Link supplies navigation behavior; it does not discover which Arabic content corresponds to an English record. If translated slugs differ, resolve the destination using a shared record identifier or route map.
Check what happens to query parameters and fragments. A catalogue's selected difficulty filter may be portable between locales if its value is a stable identifier. An English search phrase should not be silently translated or discarded without a product decision. Do not swap arbitrary text occurrences of en in the full URL.
Layouts can be retained during navigation, and navigating between distinct root layouts causes a full document load. Account for that documented behavior when designing locale boundaries. Verify both direct requests and your actual language-switch links rather than assuming that a successful hard refresh proves navigation works.
If the chosen architecture requires a document navigation for a language change, use an ordinary anchor deliberately. Preserve or explicitly discard unsaved filter and editing state according to the product contract. Do not hide a document reload behind a translation toggle that promises to preserve every client draft.
After switching, inspect the real document's lang and dir, the visible labels, and the metadata. A correct provider value in React DevTools does not establish those document properties.
Use the point at which the result changes to narrow the investigation:
| Observation | Inspect next |
|---|---|
| The initial Arabic response already declares English | Server locale resolution and the layout that owns html |
| The initial response is correct, then direction changes after mounting | Client initialization, effects and scripts that mutate the document |
| A direct Arabic request works, but the language switch does not | Its destination URL, retained providers and the root-layout boundary |
Text looks RTL while the document has no dir | CSS direction applied in place of semantic document direction |
| The URL and attributes change, but an English label remains | The message source, fallback catalog or memoized label |
These observations identify the next layer to inspect; they do not prove that every failure has one cause. Record the initial response and the post-navigation state for the same route. If you inspect only the final DOM after an effect has repaired it, the server defect disappears from the evidence. If you inspect only the server response, a later client mutation remains invisible. A language-switch regression needs both snapshots of the route's lifecycle.
Load Arabic glyphs and check the font that renders them#
The root example imports Noto Sans Arabic and applies its generated class on Arabic routes. next/font/google retrieves fonts during the build workflow and serves the resulting assets from the deployment, rather than asking the visitor's browser to fetch them from Google. Next.js font optimization documents that behavior.
The subsets option identifies subsets to preload. It is not a command that adds missing Arabic glyphs to a Latin-only font. The chosen family must actually cover Arabic, and local font files need that coverage too. The font API reference explains subset preloading and local font configuration.
Check that your global CSS does not override the generated font family on body, headings or controls. Inputs and buttons may also need font: inherit under your reset. A correctly configured root font cannot repair a component that explicitly chooses a different family.
Use DevTools' rendered-font information on Arabic headings, diacritics and body text. A network request succeeding only proves that an asset arrived. A declared font family only proves that it was requested by CSS. Neither proves which font supplied the Arabic glyphs.
Inspect the page before and after the font becomes available. display: "swap" permits fallback text while loading; check that the eventual Arabic font does not reveal clipped labels or collide with fixed-height controls. Set a readable line height and allow translated content to wrap. Avoid tracking intended for Latin display text on connected Arabic script.
For self-hosted font files, verify the production asset URLs, supported weights and licensing as part of your existing font pipeline. Development success does not establish that the deployed files are present.
Convert directional CSS where the component needs it#
Next.js does not rewrite physical CSS properties when dir changes. CSS Modules scope names, but a scoped margin-left is still a left margin. Utility classes and inline styles require the same review.
Consider a flex route card whose title comes first and difficulty label comes last. The label should sit at the row's inline end. Its English CSS currently uses an automatic left margin.
Problem:
.route-card { display: flex; align-items: baseline; gap: 0.875rem;} .route-card__grade { margin-left: auto;}Better: keep the same row and replace only the directional margin.
.route-card { display: flex; align-items: baseline; gap: 0.875rem;} .route-card__grade { margin-inline-start: auto;}The English layout retains its automatic left margin. In Arabic, inline start maps to the right, so the spacing follows the row's direction. MDN's logical properties guide explains the mapping. Review the paired pages to confirm the title and label still fit together when either wraps.
Do not add row-reverse merely because the page is Arabic. A normal flex row already follows its base direction. Preserve meaningful source order, then inspect keyboard navigation as well as box placement.
Make a separate decision for directional artwork. The catalogue's physical climbing-wall diagram represents an actual wall and should keep that geometry. Navigation arrows and progression controls may have different meaning. What to mirror in RTL covers that distinction.
Align component libraries with the document#
A design system may have its own direction setting in addition to the native document attribute. Initialize it from the same resolved locale. Otherwise the page can have correct Arabic text while a library positions adornments or menus according to LTR configuration.
Material UI, for example, documents HTML direction, theme direction and its RTL styling integration as separate setup steps. Follow the Material UI RTL guide matching your installed styling engine. Do not assume a theme property alone changes native document direction.
Avoid running two independent CSS flipping passes over the same rules. Inspect the generated rule when a physical property appears to switch correctly on the server and then changes again after hydration. The repair belongs in the styling pipeline, rather than another component-level offset.
Open a menu, dialog or tooltip through the actual production library. A portal follows its DOM placement for native direction inheritance, even when it retains React context from another branch. Global document direction helps body-mounted portals; a local RTL wrapper inside an English document may not reach them.
Keep provider placement and server style insertion consistent between the initial render and interactive updates. Review a language switch with an overlay already open, because testing only a newly opened Arabic overlay misses stale direction state.
Give mixed text and inputs their own direction contract#
Document RTL is the default, not a demand that every value be RTL. The catalogue can show a route reference such as 6274-CRUX, an equipment URL or an English route-setter note within Arabic content.
Use an isolation boundary around fixed-format references and select direction according to their content. For user-authored notes with unknown direction, consider dir="auto" on the note itself. Do not move an entire Arabic card into LTR just to make one code look correct. See nested LTR content for the relevant boundaries.
Keep Arabic labels and validation messages in the interface direction while making email, URL and telephone values explicitly LTR. A free-text route comment has a different contract from those machine-format inputs. Pass dir through wrappers to the actual native control, and preserve the text's source order in state.
Server and Client Components need the same value boundaries. A reference that is isolated in the detail page but flattened into an Arabic string by a client notification is still a bidi defect. Review the complete output path rather than deciding that server rendering or a translation library makes interpolation safe automatically.
Generate metadata for the localized page#
Arabic body content does not translate an inherited English title or description. Use the Metadata API on Server Components instead of manually inserting competing head tags. The metadata guide describes the supported exports.
This minimal app/[locale]/routes/page.jsx uses the registry and the root's metadataBase. The example catalogue represents a hall in Jordan; its Open Graph locale values are chosen explicitly rather than copied from the document language tag.
import { notFound } from "next/navigation";import { isLocale } from "../../lib/locales.js"; const copy = { en: { title: "Indoor climbing routes", description: "Browse the hall's routes, difficulty grades and setting notes.", ogLocale: "en_GB" }, ar: { title: "مسارات التسلق الداخلي", description: "استعرض مسارات القاعة ودرجات الصعوبة وملاحظات التجهيز.", ogLocale: "ar_JO" }}; async function resolvePage(params) { const { locale } = await params; if (!isLocale(locale)) notFound(); return { locale, text: copy[locale] };} export async function generateMetadata({ params }) { const { locale, text } = await resolvePage(params); return { title: text.title, description: text.description, alternates: { canonical: `/${locale}/routes`, languages: { en: "/en/routes", ar: "/ar/routes" } }, openGraph: { title: text.title, description: text.description, locale: text.ogLocale, url: `/${locale}/routes` }, twitter: { card: "summary", title: text.title, description: text.description } };} export default async function RoutesPage({ params }) { const { text } = await resolvePage(params); return <main><h1>{text.title}</h1></main>;}This is a heading-only page scaffold; add catalogue content from the same locale-aware data source. The Arabic catalogue's canonical remains its own Arabic URL. Its alternate set points to corresponding catalogue pages, rather than sending every Arabic detail page to an English homepage.
Next.js resolves relative metadata URLs using metadataBase; its metadata API reference documents the fields. For detail pages, compute actual translated record URLs instead of inheriting these catalogue-level paths unchanged.
Include the corresponding Arabic entry on English pages too. Google's localized page guidance calls for consistent alternate sets including each page itself. Only advertise a translated counterpart that exists. Language metadata cannot manufacture a missing translation.
Keep translated data separated in caches#
If a route loader returns translated setting notes, its result depends on locale as well as record identity. Include both in the loader's inputs and in any application cache key. A URL prefix alone does not distinguish results in a custom cache keyed only by a route's database ID.
Separate language-independent data, such as wall geometry, from translated descriptions where that matches your data model. That allows shared geometry without accidentally sharing an English description with an Arabic page. Keep metadata and visible content connected to the same localized record version.
Next.js caching behavior depends on the APIs and configuration in use. Do not add a caching directive merely to make a localization example static. With Cache Components enabled, the documented use cache key incorporates serializable arguments. Pass locale explicitly instead of reading an unrelated request preference inside a shared cached function.
When invalidating a translated record, account for its affected language variants and metadata. Test after warming English first and Arabic second, then reverse the order. A cold development render can miss a cache collision that appears only when another language populated the entry.
Review the document outside the successful page path#
Loading, empty, failed and not-found states are part of the Arabic route. Keep their labels translated and their layouts inside the intended direction boundary. A narrow loading placeholder does not prove that the final Arabic text will fit.
notFound() terminates the relevant render path and selects not-found handling; it does not automatically translate that handling. Next.js documents the function separately from the page that displays the result. Test both a missing climbing route under a valid Arabic locale and an unsupported locale segment.
A global error page can replace the root layout, so it needs its own document attributes and required styling. The error file documentation describes this replacement behavior. Make an explicit fallback-language choice if the normal locale resolver has itself failed.
Likewise, the optional global not-found convention bypasses normal layouts and has its own setup requirements. Consult the not-found file documentation before adopting it, especially with a root layout under a dynamic locale segment. Do not assume an Arabic wrapper in the normal catalogue reaches every framework response.
Verify the route contract in the deployed build#
Open the Arabic catalogue directly and inspect the response document before relying on client navigation. It should already declare Arabic and RTL, with the expected heading. Then test the English URL and confirm that the same deployment returns English and LTR.
Navigate between languages through the real switcher, open a detail page directly, and use browser Back. Inspect document attributes after each transition. Repeat with a warmed cache, an open overlay and a slow font response. These paths exercise different ownership boundaries than a single refreshed screenshot.
Check metadata in the rendered document for the page being tested: translated title and description, its own canonical, corresponding alternate URLs and localized sharing text. Account for the framework's metadata rendering behavior rather than assuming every tag must occupy the same place in every raw response chunk.
At narrow widths and enlarged text sizes, inspect the route card, filter controls and open overlays for clipping and horizontal overflow. A successful production build validates neither Arabic glyph coverage nor the visual position of a mixed-direction reference.
A free Ritla scan can report document direction missing, contradicted, or declared only in CSS , and html[lang] missing, non-Arabic, or contradicting detected content . If the Arabic route's document is correct but its components still fail, continue with debugging RTL layouts or converting directional CSS.