Dynamic dir and lang in Next.js
Set Next.js document language and direction from the active locale, keeping server HTML, hydration and language switches consistent.
By Omran Khleifat, Founder of Ritla
Guide12 min read
An Arabic page opens with left-to-right spacing, then moves after JavaScript runs. On another visit, the Arabic labels appear but the document still declares English. Both failures can come from code that chooses lang and dir after Next.js has already rendered the document.
Set those attributes in the root layout from a validated locale available on the server. Then make client components and language navigation follow the same choice. A component that changes the attributes later can make the final screenshot look correct while leaving the initial response wrong.
The examples use a fictional handmade-paper workshop journal with batch pages at /en-GB/batches and /ar-JO/batches. Regional locale tags make the distinction visible: language is a tag such as ar-JO, while direction is a separate value such as rtl.
Decide what each attribute means#
lang declares the language of the element's content. It does not translate that content or select its reading direction. dir establishes base direction. It does not identify the language.
For the workshop journal, the supported document settings are:
| Route locale | Document language | Document direction |
|---|---|---|
en-GB | en-GB | ltr |
ar-JO | ar-JO | rtl |
Language tags use BCP 47 syntax, as described in MDN's lang reference. Do not put an Open Graph locale such as ar_JO into lang; that is a different metadata convention. Do not put ar-JO into dir, whose values describe direction rather than language.
An application can choose a less regional document language if that accurately represents its content. The tag should express the document's language contract, not merely repeat an internal routing identifier. Keep the mapping explicit when those identifiers differ.
Changing between two supported Arabic regional locales would normally retain RTL direction, even though the language tag or formatting settings may change. Avoid treating language and direction as one boolean setting. Their relationship belongs in your supported-locale configuration.
Document language also has limits. It describes page content, not the visitor's browser menus, keyboard layout or operating-system language. In Chromium 151, checked on September 24, 2026, an Arabic page in an English browser still showed English built-in form validation copy. Do not use that browser-owned message as evidence that the document's lang attribute failed to update. Inspect the attribute and the application's own translated messages separately.
Give an explicit locale URL priority over preferences#
For /ar-JO/batches, use the route locale. A saved English preference or an English browser should not turn that address into an English document. Preferences can help choose an initial destination when the URL does not select a language.
Write down the source used for the active page:
| Situation | Suitable source for the document settings |
|---|---|
| A localized route | Its validated locale segment |
| An unprefixed application with a saved UI preference | A server-readable, validated preference |
| An entry URL choosing a destination | Negotiation followed by navigation to a locale URL |
| An English note inside an Arabic interface | A local language and direction boundary |
Do not resolve these independently in the root, a translation provider and a theme provider. An Arabic route with English client messages and an RTL theme has several conflicting answers to the same initial question.
The browser's navigator.language is not the route's identity. It is also unavailable to the server rendering the initial document. Reading it after mounting introduces a second decision after the server has already committed to another one.
Recognize the post-render repair#
Problem: this component changes the document when its effect runs. Assume the surrounding root layout initially emits English and LTR.
"use client"; import { useEffect } from "react"; export function LateDocumentLocale({ locale }) { useEffect(() => { document.documentElement.lang = locale; document.documentElement.dir = locale === "ar-JO" ? "rtl" : "ltr"; }, [locale]); return null;}The Arabic route still starts with the wrong server attributes. Effects run on the client, not during server rendering, as React documents for useEffect. On a slow load, inspect the page before this component runs instead of accepting the eventual DOM as proof of correct server output.
Moving the mutation to a layout effect changes client timing but does not make it part of the server response. An early script that patches the attributes can conceal the visual transition while preserving two sources of truth. Neither supplies the missing locale decision to the root layout.
Also distinguish a delayed correction from a hydration mismatch. If the first client render agrees with the incorrect English document and an effect changes it later, a mismatch warning is not guaranteed. The absence of a warning does not prove that the page began with the correct language and direction.
Map only the locales the application supports#
Create a pure helper in lib/document-locales.js:
export const documentLocales = { "en-GB": { lang: "en-GB", dir: "ltr" }, "ar-JO": { lang: "ar-JO", dir: "rtl" }}; export function getDocumentSettings(value) { if (typeof value !== "string" || !Object.hasOwn(documentLocales, value)) { return null; } return documentLocales[value];}This is a support registry, not a parser for every valid language tag. A tag may be valid BCP 47 while unsupported by the application's translations. Route matching can use the canonical spelling shown here and redirect accepted aliases according to an explicit policy.
Avoid locale === "en" ? "ltr" : "rtl". That would classify every other input as RTL, including unsupported values. Likewise, do not use an Arabic language declaration as a substitute for dir="rtl".
The registry contains static settings shared by requests. Do not add a mutable currentLocale next to it and change that variable during rendering. Request-specific state belongs in the current route or request context, not in a process-wide assignment.
Set both attributes in the root that owns html#
Better: use this structure for the route-based journal:
app/ [locale]/ layout.jsx batches/ page.jsxlib/ document-locales.jsThere is no parent app/layout.jsx rendering another document. The root is app/[locale]/layout.jsx:
import { notFound } from "next/navigation";import { documentLocales, getDocumentSettings} from "../../lib/document-locales.js"; export function generateStaticParams() { return Object.keys(documentLocales).map((locale) => ({ locale }));} export default async function LocaleLayout({ children, params }) { const { locale } = await params; const settings = getDocumentSettings(locale); if (!settings) notFound(); return ( <html lang={settings.lang} dir={settings.dir}> <body>{children}</body> </html> );}Both attributes now come from one validated setting during server rendering. Unsupported route values follow the application's not-found handling instead of becoming arbitrary document language values.
The Next.js layout reference supports root layouts beneath a dynamic locale segment. Its params are asynchronous and include dynamic segments from the root down to that layout. A layout above [locale] cannot simply access that descendant segment through its own parameters.
Do not duplicate html and body inside a nested locale layout while leaving an English document above it. Either move document ownership as shown or use another server-resolved locale architecture that actually reaches the owning root.
Here, “dynamic attributes” means their values depend on the locale. It does not mean the application must read a cookie on every request. Locale-specific pages can have their correct attributes generated ahead of time when the rest of their rendering permits it.
Carry the initial choice through hydration#
The server-rendered attributes and the first client render must describe the same document. React's hydration reference treats mismatches as bugs and does not guarantee that attribute differences will be repaired.
Pass the server's validated locale and its translated messages into interactive components or their provider. Do not initialize that provider to English, then switch it to Arabic after reading the document. The root should not have to wait for the provider, and the provider should not need to rediscover the root's decision.
A theme or component library may also require a direction setting. Supply settings.dir from the same configuration. Its internal context does not replace the native document attribute, but agreement avoids one layer positioning controls for LTR while another renders RTL.
Do not add suppressHydrationWarning to silence a reproducible locale mismatch. It does not select the correct locale, translate labels or supply the right initial direction. Next.js's hydration-error guidance describes suppression as an escape hatch, not a synchronization strategy.
Watch for surviving legacy code after moving the attributes to the server. A root layout can emit the correct Arabic settings, then an old provider effect can overwrite them with its English default. Remove competing document writers instead of adding another effect that switches them back.
Make the language switch navigate to the corresponding route#
A language toggle that changes only React messages leaves the address and server inputs unchanged. For this example, navigate between the two batch URLs.
This minimal app/[locale]/batches/page.jsx provides the corresponding links and translated heading:
import Link from "next/link";import { notFound } from "next/navigation";import { getDocumentSettings } from "../../../lib/document-locales.js"; const headings = { "en-GB": "Paper-making batches", "ar-JO": "دفعات صناعة الورق"}; export default async function BatchesPage({ params }) { const { locale } = await params; if (!getDocumentSettings(locale)) notFound(); return ( <main> <h1>{headings[locale]}</h1> <p> <Link href="/en-GB/batches" lang="en-GB" dir="ltr">English</Link> {" · "} <Link href="/ar-JO/batches" lang="ar-JO" dir="rtl">العربية</Link> </p> </main> );}The native language names receive their own language and direction declarations. The links select concrete destinations; they do not mutate the existing document before navigation completes.
Test the switch in both directions and through browser Back. Shared layouts can be retained during navigation, so a successful direct request does not establish every transition's behavior. Distinct root layouts cause a full document load. Account for the route architecture instead of assuming every language change preserves the same client tree.
If the design deliberately uses a document navigation for locale changes, use an ordinary anchor. Decide what happens to unsaved journal edits before choosing that interaction. For a larger application with translated record slugs, resolve the equivalent record URL rather than replacing a locale substring in the full address.
Treat cookie-based document language as a different architecture#
An internal application may intentionally use one unprefixed URL and choose its UI locale from a saved preference. That still needs a server decision. For that alternative, a helper such as lib/preferred-document-locale.js can read the request cookie:
import { cookies } from "next/headers";import { getDocumentSettings } from "./document-locales.js"; export async function getPreferredDocumentSettings() { const store = await cookies(); const saved = store.get("paper-ui")?.value; return getDocumentSettings(saved) ?? getDocumentSettings("en-GB");}An unprefixed root can await that result and use its two attributes, just as the route-based root uses its route result. This helper is an alternative source; do not add it to the example locale root to override an explicit Arabic URL.
cookies() is asynchronous and reads request-time data. Next.js documents its rendering implications, including Cache Components constraints, in the cookies API. Do not assume one statically shared document can represent both cookie-selected languages without a supported rendering and caching strategy.
When the preference changes, coordinate the next server render with the new preference. Changing the cookie value and changing client messages are not, by themselves, proof that the current root has been rendered from it. Inspect the resulting document after the application's navigation or refresh path.
Using request headers instead has the same ownership question. The headers API exposes incoming headers, not a reason to trust an arbitrary locale value. Validate any resolved setting and keep shared cache variants separated where the application or deployment caches locale-dependent HTML.
For an unprefixed implementation, run two isolated browser sessions against the same address. Give one session paper-ui=en-GB and the other paper-ui=ar-JO, then request the page in alternating order after warming the deployment's caches. Each response should retain the settings selected for its own request. If they bleed between sessions, inspect shared response caching and application-level memoization rather than adding another client correction.
For the route-based journal, invert the test: request the Arabic URL with a saved English preference and an English browser locale. It should remain Arabic. This distinguishes a deliberate cookie-selected architecture from an accidental cookie override inside an explicitly localized route.
Inspect attributes and CSS as separate evidence#
An Arabic page can look RTL because a stylesheet sets direction: rtl while its dir attribute is missing. It can also declare RTL correctly while a more specific CSS rule forces a content region back to LTR.
Use this browser-console inspection on the loaded page:
const root = document.documentElement;const main = document.querySelector("main"); ({ langAttribute: root.getAttribute("lang"), dirAttribute: root.getAttribute("dir"), rootCssDirection: getComputedStyle(root).direction, mainCssDirection: main ? getComputedStyle(main).direction : null, semanticRtl: root.matches(":dir(rtl)")});This reads both declarations and resolved CSS. It does not alter the document. Compare the result with the selected route, then inspect the winning direction rule if CSS disagrees with the intended HTML setting.
:dir(rtl) follows semantic direction, not a CSS-only direction declaration. An attribute selector such as [dir="rtl"] has another behavior: it matches the explicit attribute on that element, rather than all descendants inheriting it. MDN's :dir() reference explains the distinction.
Make language-specific selectors compatible with regional tags. A rule written for an exact lang="ar" attribute will not match the literal lang="ar-JO" value. Review whether the rule should use :lang(ar) or another deliberate language match, rather than changing a correct document tag to satisfy a brittle selector.
Do not confuse this inspection with an RTL layout audit. Correct root attributes do not mirror physical left offsets or make a mixed identifier isolated. Use direction attributes versus CSS direction when those layers disagree.
Trace the code that changes the document#
If the response starts correctly but the hydrated document changes, capture the writer. In Chrome DevTools, select the html element in Elements, open its context menu, and choose Break on > Attribute modifications. Reproduce the language transition that changes lang or dir. The paused call stack can identify the initializer or effect performing that mutation. Chrome's breakpoint documentation describes this debugging facility.
Search that code path for a default locale, a browser-language lookup or a second state store initialized independently of the route. Remove or reconcile that ownership conflict. Adding a timer to reapply Arabic only changes which writer happens to run last.
An attribute breakpoint does not explain a CSS-only direction change. If both HTML attributes remain correct while a region changes direction, inspect that region's matched styles and any class or stylesheet updates instead. Conversely, observing the correct computed direction does not establish that the language tag is correct.
Record both values at the time of the failure. A root that changes only dir can leave Arabic content declared English; one that changes only lang can leave the layout LTR. Treat the pair as one application-level decision even though the browser exposes two independent attributes.
Keep local exceptions local#
The workshop journal can contain an English supplier note inside an Arabic interface. Give that note its own lang and dir rather than changing the document. A fixed-format batch reference such as 3579-PULP similarly needs a value-level boundary when embedded in Arabic text.
Do not use dir="auto" on the whole document to infer interface direction from whichever text arrives first. The application already knows the interface locale. Automatic direction is useful for suitable unknown-direction content, not for rediscovering that application setting.
An embedded editor, email value or other inherently LTR region may intentionally differ from the document. Review those overrides according to their content contract. Adding RTL to every descendant would erase legitimate exceptions.
Portals expose why the document boundary matters. A preview can retain its React translation context while its native nodes render elsewhere in the DOM. React's portal documentation distinguishes those relationships. A portal mounted under the document body can inherit its direction, while one mounted inside an explicitly LTR host needs separate review.
Also inspect attributes within a portaled subtree if a library sets its own direction prop. Correct global attributes do not remove an explicit local override. Nested LTR content explains how to scope those boundaries without changing the rest of the page.
Verify replacement documents as well as normal pages#
A root layout does not own every possible fallback response. Next.js's global-error.jsx can replace the root layout and must define its own html and body. Its language and direction need an explicit fallback policy, as described in the error-file documentation.
Do not assume the failing locale resolver is available to recover the locale in that fallback. Choose a supported way to supply the known setting or define an intentional fallback language. The displayed recovery text and the fallback document attributes should agree.
The optional global not-found convention can also bypass ordinary layouts. The not-found documentation describes its separate requirements. Test a missing batch route beneath a valid Arabic locale separately from an unsupported locale or unmatched URL.
For an ordinary loading state inside the locale document, the root attributes should already be correct. Delayed batch data should not make the document temporarily English. A late translation or font request is a different loading concern from choosing the document's base language and direction.
Check the first response and the actual navigation path#
Use more than one observation of the same route:
| Evidence | What it helps establish |
|---|---|
| Initial document response | Which attributes the server emitted |
| Page loaded with JavaScript disabled | Whether the server result depends on a later repair |
| Hydrated document | Whether a client initializer overwrote the settings |
| Real language switch and browser Back | Whether navigation preserves the route contract |
| Document and a known content element's computed styles | Whether CSS overrides semantic direction |
For a project already configured with Playwright and a baseURL pointing at this example application, this test exercises the normal language switch:
import { test, expect } from "@playwright/test"; test.use({ locale: "en-GB" }); test("batch routes keep document language and direction aligned", async ({ page }) => { await page.goto("/en-GB/batches"); await expect(page.locator("html")).toHaveAttribute("lang", "en-GB"); await expect(page.locator("html")).toHaveAttribute("dir", "ltr"); await page.getByRole("link", { name: "العربية", exact: true }).click(); await expect(page).toHaveURL(/\/ar-JO\/batches$/); await expect(page.locator("html")).toHaveAttribute("lang", "ar-JO"); await expect(page.locator("html")).toHaveAttribute("dir", "rtl"); await expect(page.locator("html")).toHaveCSS("direction", "rtl"); await expect(page.getByRole("heading", { level: 1 })) .toHaveText("دفعات صناعة الورق"); await page.goBack(); await expect(page.locator("html")).toHaveAttribute("lang", "en-GB"); await expect(page.locator("html")).toHaveAttribute("dir", "ltr");});Playwright's retrying assertions wait for the expected navigation result. That makes this an eventual-state test. It can still pass if a client effect repaired the attributes late, so pair it with an initial-response or JavaScript-disabled check before accepting a no-flash claim.
For the initial-response check, inspect the document request itself in the Network panel. Do not substitute a client-side navigation payload or a DOM serialization captured after hydration. Confirm that the opening html element already carries the intended pair. Then compare it with the hydrated result for that same URL. When the response is correct and a visual shift remains, investigate font loading, delayed styles and component geometry rather than assuming every shift is a late direction change.
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 route attributes are correct but one region still behaves differently, continue with RTL direction not working or language versus direction to inspect that boundary.