Skip to content

Testing Arabic pages in Next.js

Learn to test Arabic Next.js routes across server rendering, hydration, locale switches, metadata, caching and preview deployments.

By , Founder of Ritla

Guide14 min read

An Arabic route can pass a screenshot review after loading and still deliver English document attributes in its first response. A language switch can translate the page heading while leaving a shared navigation panel in English. Neither failure is visible in a component test that supplies the correct locale itself.

Testing Arabic pages in Next.js means following the locale through the request, server output, hydration and subsequent navigation. Development alone is insufficient evidence: prerendering, deployed routing and cached responses need their own tests. Run the browser suite against a production build, then repeat the important journeys on the actual preview deployment.

The examples below use a fictional equipment-maintenance portal with English and Arabic routes, a maintenance-request screen and a request-history panel. They target the App Router with awaited route parameters. For a Pages Router application, keep the same testing boundaries, but use its routing and document APIs rather than copying App Router files.

Build a route matrix before writing assertions#

Start with URLs and the states a visitor can reach. Testing one Arabic landing page says little about an authenticated request screen, a generated detail page or a translated error boundary.

For each selected route, record its English counterpart, expected document language and direction, translation source, metadata and rendering strategy. Include one route with remote content if the app has one. If everything is static, test the generated output instead of inventing a server-rendering requirement.

JourneyWhat to verify
Open /ar/maintenance directlyArabic server content, Arabic document language, RTL direction
Switch from /en/maintenanceURL, page content, shared controls and document attributes agree
Open a request-history itemCorrect record and locale survive a nested route change
Refresh an Arabic detail URLThe deployed server resolves the same page without prior navigation
Use Back and ForwardLocale, active navigation and visible content remain consistent
Request an unavailable translationThe agreed missing-content behavior appears without silent English substitution

Add a narrow viewport and a realistic long Arabic message to the maintenance screen. Use a fixed record so screenshots remain comparable. Select a fixture with an empty history, another with a long history, and one failed submission. These states exercise different markup even when they share a URL.

Keep the expected locale explicit in test data. If a test derives its expectation from the same cookie or translation helper as the implementation, both can make the same mistake and the test still passes.

Check the server document before hydration#

Inspect the response for an Arabic deep link before clicking anything. The document should already declare Arabic language and right-to-left direction. Translating a subtree cannot repair a contradictory document root.

This is a broken response for the maintenance screen:

html
<html lang="en" dir="ltr">  <body><main><h1>طلبات صيانة المعدات</h1></main></body></html>

Adding direction: rtl to main can make that region look plausible while the document remains incorrectly declared. Language and direction are separate attributes; lang="ar" does not supply dir="rtl". The W3C guidance on document direction recommends declaring the overall direction on html.

For an App Router tree whose root layout lives under the locale segment, derive both attributes there:

tsx
// app/[lang]/layout.tsx, with no app/layout.tsx above itimport type { ReactNode } from 'react';import { notFound } from 'next/navigation'; export default async function LocaleLayout({ children, params }: {  children: ReactNode;  params: Promise<{ lang: string }>;}) {  const { lang } = await params;  if (lang !== 'ar' && lang !== 'en') notFound();   return (    <html lang={lang} dir={lang === 'ar' ? 'rtl' : 'ltr'}>      <body>{children}</body>    </html>  );}

This illustrates one supported tree, not a layout to paste beneath an existing document root. Next.js permits a root layout under a dynamic segment. A nested layout inside an existing root must not introduce a second html or body.

Verify the response attributes separately from computed CSS direction in the browser. Then repeat on the English route. An RTL fix that makes both languages RTL is still a regression. R001 covers document direction missing, contradicted, or declared only in CSS; R002 covers html[lang] missing, non-Arabic, or contradicting detected content.

Separate server-output tests from hydrated-page tests#

A useful pair of tests asks two different questions: what arrived from the server, and what remained after the client became interactive? A final screenshot answers neither question about the earlier state.

For server inspection, use the Network panel's document response, or an HTTP client that saves the complete response body. Search the actual opening html element, not an arbitrary dir string inside serialized component data. Check a known server-rendered heading too. An Arabic dictionary embedded in a script is not evidence that the visible server content is Arabic.

For a static maintenance heading, a separate Playwright file can also test the parsed page without application JavaScript:

ts
// tests/arabic-document.spec.ts, using the baseURL configured belowimport { test, expect } from '@playwright/test'; test.use({ javaScriptEnabled: false }); test('Arabic maintenance document works before hydration', async ({ page }) => {  await page.goto('/ar/maintenance');  await expect(page.locator('html')).toHaveAttribute('lang', 'ar');  await expect(page.locator('html')).toHaveAttribute('dir', 'rtl');  await expect(page.getByRole('heading', {    name: 'طلبات صيانة المعدات', exact: true,  })).toBeVisible();});

Keep this test scoped to content intended to arrive without client execution. It does not establish that a client-only history widget works, or that streamed metadata is delivered correctly. Test those with JavaScript enabled and inspect their relevant responses separately.

During the interactive run, capture browser errors and inspect hydration warnings. Next.js defines a hydration mismatch as a difference between server output and the initial browser render. A server dictionary selected from the URL and a client dictionary selected from localStorage can disagree. Resolve the initial locale consistently and pass it to the client provider.

Do not suppress the warning to make the test green. First identify which text, attribute or formatting decision differs.

Use the failing boundary to narrow the investigation:

ObservationInspect next
Initial document is English, final page is ArabicServer locale resolution and client-only translation initialization
Direct Arabic load passes, language switch failsRetained provider state, shared layouts and counterpart routing
Body is Arabic, title is EnglishMetadata locale inputs and parent defaults
Failure changes with visit orderBrowser state, cached data inputs and deployment cache behavior
Text assertions pass, identifier looks reorderedBidi boundaries and visual evidence

Treat these as starting points, not proof of a cause. Save both the initial response and the final DOM before changing code. That pair distinguishes a server-selection problem from a later client replacement, and makes a regression test much more specific.

Make date formatting reproducible#

A maintenance appointment rendered using environment defaults is a separate source of disagreement. Without explicit options, date formatting depends on the runtime's locale and time zone. MDN documents these defaults and the available options.

For a portal whose appointments belong to the Amman time zone:

ts
const appointment = new Date('2031-02-17T21:40:00Z');const formatter = new Intl.DateTimeFormat('ar-JO', {  dateStyle: 'long',  timeStyle: 'short',  timeZone: 'Asia/Amman',  calendar: 'gregory',  numberingSystem: 'arab',});const appointmentLabel = formatter.format(appointment);

Use the same instant and options on both sides, then verify the result in the deployed runtime. For a visitor-local appointment display, the product requirement is different: establish that visitor's zone explicitly or show a stable initial value before applying the client preference. Do not assign the server's time zone to the visitor by accident.

Avoid a universal exact-string assertion across unrelated runtime versions. Assert the required date and formatting options, and keep visual expectations tied to a controlled environment. If exact initial text must match, pass the server-formatted label into the initial client render.

Test language switching as a navigation journey#

A direct Arabic request and an English-to-Arabic transition exercise different paths. Both belong in the suite.

Open the English maintenance screen, expand the history panel, switch language using the actual control, then navigate to a request detail. Assert the destination URL, document attributes, heading, panel labels and an accessible name. Refresh there. Return with Back and repeat in the opposite direction.

Do not demand client navigation for its own sake. Next.js documents that navigation across different root layouts causes a full page load. The contract is that the resulting route is internally consistent, whichever navigation mechanism the architecture uses. Shared layouts can also be reused during navigation, so a single screenshot of the destination does not replace a journey test. See the layout behavior and caveats.

Watch for a client translation provider initialized once from an English prop, a retained request-history label, or a locale switcher that changes only the path prefix. If translated slugs differ, the switcher needs the counterpart URL for that content, not a string replacement.

Where the history panel should reset on locale change, test that requirement explicitly. Where an unsent request should be preserved, check its text and validation state after switching. Remounting every component may clear stale translations, but it can also discard the user's work. Decide the intended behavior before choosing a reset strategy.

Exercise locale negotiation independently. Open an explicit Arabic URL in a fresh context with English browser preferences, then an explicit English URL with Arabic preferences. A product may redirect the unprefixed entry route according to preferences while treating a locale-prefixed URL as an explicit choice. Write assertions for that policy, including cookie precedence, rather than assuming every app negotiates the same way.

The App Router internationalization guide shows locale segments and preference-based routing. Pages Router projects have different built-in internationalization behavior, including automatic document language handling. Check direction separately in either router.

Verify metadata as a second output of each route#

An Arabic heading does not prove that a route has Arabic search and sharing metadata. Test a deep page whose title differs from the layout default. For an indexable Arabic maintenance page, the expected canonical should identify that Arabic page, and alternate links should identify real equivalents.

For a route with a fixed Arabic title, this English export is wrong even if the body dictionary is correct:

ts
export const metadata = {  title: 'Equipment maintenance requests',  description: 'Submit and track requests for equipment repairs.',};

A localized export for the same page could be:

ts
import type { Metadata } from 'next'; export const metadata: Metadata = {  title: 'طلبات صيانة المعدات',  description: 'أرسل طلب صيانة للمعدات وتابع حالة الإصلاح وموعد الزيارة.',  alternates: {    canonical: 'https://maintenance.example/ar/maintenance',    languages: {      ar: 'https://maintenance.example/ar/maintenance',      en: 'https://maintenance.example/en/maintenance',    },  },};

The example origin is fictional; substitute the intended public origin. In an app/[lang]/maintenance/page.tsx shared by both languages, return the corresponding values from generateMetadata using the validated route locale. Do not return the Arabic object for every locale.

Inspect the resolved tags. Parent title templates can alter the final title, and metadata objects are shallowly merged: setting a page's openGraph object can replace the parent's nested values. Check the final OpenGraph locale, title and description, plus Twitter metadata, rather than assuming inheritance preserves them. These behaviors are documented in the Metadata API reference.

Use absolute expected URLs in assertions. Merely checking that a canonical contains /ar/ misses the wrong host, wrong record or wrong pathname. Open each alternate target and confirm that it is the equivalent content, not an unrelated landing page. Missing translations should not produce invented alternate URLs.

R003 covers an alternate set lacking any Arabic entry on an Arabic page. R004 covers a majority-Latin title or meta description on an Arabic page. R005 covers untranslated OpenGraph/Twitter metadata or missing/invalid og:locale. R006 covers a canonical pointing at a different-locale variant. Exact counterpart identity and reciprocal links still need explicit assertions.

Account for streamed metadata#

For dynamically rendered pages, Next.js can send visible UI before generateMetadata resolves. Metadata delivery also depends on the requesting user agent. Prerendered pages resolve their metadata at build time. The metadata guide explains these distinctions.

A test that reads only the first response chunk can report metadata as missing when it arrives later. A selector restricted to head can also make the wrong assumption about a streaming response. In browser tests, use a retrying title assertion and inspect metadata across the resolved document. In HTTP tests, consume the complete response.

For pages shared outside the app, also request the preview with a relevant HTML-limited crawler user agent, such as facebookexternalhit, and inspect its complete document response. Check the actual configuration used by the project. Do not disable streaming globally just to satisfy a test that stops reading too soon.

Make locale part of the cached content's identity#

If Arabic changes depending on which language was visited first, investigate cache inputs before changing CSS.

Reproduce in both orders: request the English maintenance page, then Arabic; start a fresh browser context and request Arabic, then English. Repeat each URL. Compare the heading, one record-specific description and metadata. A fresh context clears client state, not the deployed server cache, so record cache state rather than calling every first browser visit a cold server request.

Trace locale through each data boundary. Does the CMS request actually include it? Does a custom cache key distinguish language variants? Are page content and metadata requesting the same translated record? Do not conclude that /ar/ and /en/ URLs alone protect a shared data helper.

With Cache Components enabled, use cache includes serializable function arguments in its cache key. Pass locale as an explicit input when the result varies by language. Read request cookies or headers outside the cached scope, then pass the resolved value in. The use cache reference describes both the key and request-time API restrictions.

For applications using server fetch caching, inspect the actual request URL and options. Next.js distinguishes cached requests by request inputs, including headers; a correctly supplied locale header need not be duplicated in the URL. What matters is that the locale reaches the request and any intermediate custom cache. Consult the fetch reference for the installed version instead of assuming an older release's defaults.

Test translation updates too. Change one Arabic maintenance description in a controlled environment, trigger the application's intended revalidation path, and check both the visible record and its metadata. Verify English remains correct. A fix that bypasses every cache can hide the missing input without validating the intended caching design.

Run browser assertions against the production build#

Keep quick component tests for translation selection and pure formatting functions. They cannot establish whether the deployed route returns the right document or whether an Arabic label fits its rendered box.

Next.js recommends running Playwright against production code. In a standard project, build with next build, serve with next start, then run the suite. This configuration starts a local production server or targets an existing preview:

ts
// playwright.config.ts, after installing @playwright/test and its browsersimport { defineConfig } from '@playwright/test'; const previewURL = process.env.PREVIEW_URL; export default defineConfig({  testDir: './tests',  use: { baseURL: previewURL || 'http://127.0.0.1:3000' },  projects: [    { name: 'chromium', use: { browserName: 'chromium' } },    { name: 'firefox', use: { browserName: 'firefox' } },    { name: 'webkit', use: { browserName: 'webkit' } },  ],  webServer: previewURL ? undefined : {    command: 'npx next build && npx next start --hostname 127.0.0.1',    url: 'http://127.0.0.1:3000',    reuseExistingServer: false,    timeout: 180_000,  },});

Set PREVIEW_URL to the full deployed origin to reuse the tests there. Adapt the start command for a standalone server or hosting adapter. Keep required build-time environment values consistent with the deployment being tested.

The Playwright projects configuration runs these tests across the named browser engines. Install their binaries using npx playwright install. Choose coverage according to the product's support policy and keep separate screenshot baselines per project. A Chromium result is not evidence of a Firefox or WebKit result. Also distinguish a narrow desktop viewport from a real mobile-device check: use the former to expose responsive layout failures and the latter to verify touch controls, the on-screen keyboard and device-specific text rendering.

For statically generated content, check a generated Arabic route and a valid route outside the build-time set if on-demand generation is supported. generateStaticParams behaves differently during development and build, and is not rerun during revalidation. The static-parameter reference explains the lifecycle. An English-only generated route list needs a production test, not another translation snapshot.

Add visual assertions without confusing text and appearance#

Use semantic assertions for document attributes and translated labels. Use rendered evidence for clipping, wrapping and bidirectional appearance. Neither substitutes for the other.

This browser test establishes a small Arabic baseline at a narrow width:

ts
// tests/arabic-maintenance.spec.tsimport { test, expect } from '@playwright/test'; test('Arabic maintenance screen at narrow width', async ({ page }) => {  await page.setViewportSize({ width: 390, height: 844 });  await page.goto('/ar/maintenance');  await expect(page.locator('html')).toHaveAttribute('dir', 'rtl');  await expect(page.locator('html')).toHaveCSS('direction', 'rtl');  await expect(page.getByRole('heading', {    name: 'طلبات صيانة المعدات', exact: true,  })).toBeVisible();  await page.evaluate(async () => { await document.fonts.ready; });  const extraWidth = await page.evaluate(() =>    document.documentElement.scrollWidth -    document.documentElement.clientWidth  );  expect(extraWidth).toBeLessThanOrEqual(1);  await expect(page).toHaveScreenshot('maintenance-ar-narrow.png', {    fullPage: true,  });});

The one-pixel allowance is a chosen test tolerance, not a browser guarantee. MDN defines scrollWidth as the content width, including content outside the visible area. This assertion checks document width; it cannot establish that text inside an overflow-hidden button is readable. Review component screenshots and interact with controls too.

document.fonts.ready waits for the document's font-loading and layout work to settle. It does not prove that the intended font supplied the Arabic glyphs. Inspect rendered fonts and failed font requests when the screenshot looks different.

Keep a separate slow-network review for the period before the font arrives. The settled screenshot deliberately excludes that interval. Verify that a maintenance request remains readable and its submit control remains usable during the fallback state. If a dialog introduces text or fonts later, wait and capture that newly opened state as well; an earlier font-ready check says nothing about content that was not present yet.

Approve the initial Arabic screenshot manually. Keep the baseline and subsequent runs in the same browser and operating-system environment, as Playwright's visual-comparison guidance recommends. Updating snapshots automatically after a failure only records the failure as the new expectation.

For a mixed-direction fixture, use a maintenance work-ticket identifier such as 864219-57-6038 after an Arabic label. In Chromium 151 measurements, this pattern's unisolated groups display left to right as 6038-57-864219. The ticket's fixed group order should survive; an Arabic reader should not have to reinterpret it as a range. Isolate the identifier value, then verify its appearance in your supported browsers. The bidi-isolation guide covers the markup.

A textContent assertion or copy-and-paste test still returns logical text order and can pass while the displayed identifier is wrong. Keep this case in the visual review.

Exercise loading, errors and content outside the page subtree#

Throttle a request-history response so the loading state remains visible. Then fail it deliberately. Review the loading label, error message, retry control and resulting layout in Arabic. A translated success screen does not cover loading.tsx, error.tsx, validation responses or a missing-record view.

Test missing records under a valid Arabic locale separately from completely unmatched URLs. Root-level fallbacks may not receive the same locale context as the page you expected. Inspect the actual document and fallback text rather than inferring their language from the requested prefix.

Do not use status alone to decide whether a request-detail page exists. Next.js documents that a not-found response can retain status 200 after streaming starts. Check the missing-record UI and indexing directive alongside the status. Otherwise an Arabic fallback can be misclassified as a successfully rendered maintenance record, or a test can reject expected streaming behavior while missing the untranslated fallback itself.

Open the maintenance form's confirmation dialog and any portaled selector. If direction was applied only to a page wrapper, content rendered elsewhere in the document needs inspection. Check the overlay's computed direction, labels, alignment and focus behavior. Follow keyboard focus through opening, submission, errors and closing. A mirrored screenshot cannot establish a usable focus sequence.

For client-fetched data, wait for a specific visible state before taking the final screenshot. A loaded heading is not evidence that history, permissions or validation have resolved. Capture the loading state separately instead of adding an arbitrary delay that sometimes hides it.

Repeat at widths just before and after the application's navigation breakpoint, then at the narrowest supported width. Open the same overlays in each state. Check the English version after any shared CSS change. Use debugging RTL layout problems when a mismatch points to physical positioning, inherited direction or an overflowing element.

Gate the release on the preview's actual behavior#

The preview is where routing rules, authentication, external content and deployed assets meet. Run the route matrix there with the same test records used locally. Make sure authentication reaches the intended Arabic page rather than a login screen whose successful load makes the test appear healthy.

  • Open and refresh Arabic deep links, including one detail route.
  • Switch both ways, then use Back and Forward with a shared panel open.
  • Compare initial document attributes with the interactive page.
  • Assert exact metadata URLs and inspect a sharing-crawler response.
  • Exercise both locale request orders and a translation revalidation.
  • Review narrow-screen screenshots, loading, failures and dialog interactions.

Check preview indexing policy separately from locale identity. A preview may intentionally be non-indexable while emitting canonical URLs for the public site. Do not rewrite those canonicals to the preview host merely because the test uses that host. Conversely, a production build must not inherit preview-only indexing restrictions.

When reporting a failure, include the preview URL, build identifier, route, previous locale, viewport and whether the problem occurred before or after interaction. Attach the relevant response fragment or screenshot. “Arabic is wrong” is difficult to reproduce; “Arabic detail refresh returns English root attributes after an English visit” names a testable defect.

A free Ritla scan of the Arabic preview page can surface a contradictory document direction or a canonical pointing at another locale; use the navigation tests above to investigate how that state was reached. For the next release, carry these journeys into testing Arabic releases, especially when a change touches shared layouts, metadata or cached translations.

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