Localization in React
Set up localization end to end
Section titled “Set up localization end to end”This recipe connects the server, the Arc root, Cratis Components and a language selector. The bridge and LanguageSelector need @cratis/components 4.80.0 or later, imported from @cratis/components/Localization. Translating Components with Arc catalogs through value.catalog needs 4.82.0 or later.
-
Set
Cratis:Arc:Localizationin the server’sappsettings.json, as described in request localization:{"Cratis": {"Arc": {"Localization": {"SupportedUICultures": ["en", "nb-NO"],"DefaultUICulture": "en","Aliases": { "no": "nb-NO" }}}}} -
Put the frontend languages, default and optional aliases in
localization.json:{"$schema": "./node_modules/@cratis/arc/dist/localization/schema.json","languages": ["en", "nb-NO"],"default": "en","aliases": { "no": "nb-NO" }}Generate the localization policy with
cratis-l10n buildor the Vitelocalization()plugin. If the policy is one directory above the Vite root, registerlocalization({ root: '..' })and adjust the schema path relative tolocalization.json. Runcratis-l10n check --server path/to/appsettings.jsonto check that the client and server agree. Create the store from the generated policy:import { createLocale } from '@cratis/arc/localization';import { localizationPolicy } from './generated/localization-loaders';export const locale = createLocale({...localizationPolicy,storageKey: 'ui-language',}); -
Pass the store to
<Arc>. No initialization effect or header callback is needed, and every command and query sends the active language. -
Register the Components catalogs and bridge Arc’s language into Components.
ArcComponentsProviderfollowsuseLocale()for both the UI language and the regional format; the catalog supplies the translated Components text for the active language.import { useEffect, useState, type ReactNode } from 'react';import { createCatalogRegistry, type CatalogTranslator } from '@cratis/arc/localization/catalog';import { Arc, useLocale } from '@cratis/arc.react';import { ArcComponentsProvider, LanguageSelector } from '@cratis/components/Localization';import { localizationPolicy, packLoaders } from './generated/localization-loaders';import { locale } from './locale';const componentsCatalogs = createCatalogRegistry({default: localizationPolicy.defaultLocale,catalog: [packLoaders.components],});function LocalizedComponents({ children }: { children: ReactNode }) {const tag = useLocale()?.locale;const [catalog, setCatalog] = useState<CatalogTranslator>();useEffect(() => {if (!tag) return;let cancelled = false;void componentsCatalogs.load(tag).then(loaded => {if (!cancelled) setCatalog(loaded);});return () => { cancelled = true; };}, [tag]);return <ArcComponentsProvider value={{ ...(catalog && { catalog }) }}>{children}</ArcComponentsProvider>;}export function App() {return (<Arc locale={locale}><LocalizedComponents><LanguageSelector /><Content /></LocalizedComponents></Arc>);} -
LanguageSelectorwith no props reads Arc’s supported languages and current language and callssetLocalewhen the user picks one. The page does not reload, query results refresh and input values are preserved.
Read translated text in your own components with useTranslation or useLocale()?.t; see Translate with ICU catalogs.
Read the locale in a library
Section titled “Read the locale in a library”Place any UI providers that consume Arc’s locale inside <Arc>. ArcLocale is the contract that library providers read from ArcContext.locale. Application code gets the same object from useLocale(). Both are exported from @cratis/arc.react. If the provider didn’t configure localization, both return undefined, and useTranslation() uses the catalogue fallback.
| Member | Meaning |
|---|---|
locale |
The active UI language tag. |
supported |
The supported UI language tags. |
formatLocale |
The regional format for Intl. It follows locale unless set separately. |
t?, tWithLocale? |
Translate against the catalogs loaded for this snapshot. Present when a catalogRegistry is configured. |
setLocale(tag) |
Switches the UI language without waiting for the result. |
setLanguage?(tag) |
Switches the UI language and resolves to whether it took effect. |
setFormatLocale?(tag?) |
Changes the regional format. undefined follows the UI language again. |
localeDirection(tag) from @cratis/arc/localization returns 'ltr' or 'rtl' for a language tag.
<Arc locale={…}> also accepts stable LocaleOptions. Keep the store or options reference stable across renders. Locale changes refresh query results and re-establish live subscriptions instead of remounting the app, so input values and local React state are preserved. A localized root sets <html lang> and <html dir> (rtl for languages such as Arabic and Hebrew, ltr otherwise) and restores the previous values when removed. An application that sets dir itself sees it replaced while the root is mounted. A document has only one language; keep independently localized roots in separate documents if their document languages matter.
Each localized Arc root has a child of the application’s DI container. Queries from an injected IQueryProvider and proxies injected into MVVM view models use that root’s locale and headers. To create a proxy explicitly, inject ArcClientFactory from @cratis/arc.react and call its create(ProxyType) method. Browser roots and roots without a locale still configure the global transport and identity fallback for unscoped clients. A root never sets Globals.locale, and localized server renders do not change global settings.
Translate with ICU catalogs
Section titled “Translate with ICU catalogs”Pass a catalogRegistry from @cratis/arc/localization/catalog in the locale options. Read useLocale()?.t?.('profile.greeting', { name }) in React to subscribe to translation changes, or inject LocaleService from @cratis/arc/localization in TypeScript to call t against the current snapshot. Use setLanguage(tag) to await a change. It publishes the selected language and its loaded messages together, returning false if the language is unsupported, its catalog fails to load, or a newer supported request supersedes it. The existing setLocale(tag) remains a fire-and-forget action.
For IDs known when you write the code, cratis-l10n build generates typed accessors to use next to t(): m.hours.registered({ count }) is the same text as t('app.hours.registered', { count }). Set Globals.locale to the same store you pass to <Arc> once at browser startup, and call useLocale() in the component so it renders again when the language changes:
import { useLocale } from '@cratis/arc.react';import { m } from './generated/messages';
export function HoursHeader({ count }: { count: number }) { useLocale(); return ( <header> <h1>{m.hours.title()}</h1> <span>{m.hours.registered({ count })}</span> </header> );}Set initialLocale for a choice supplied by your app or the user’s profile. Otherwise the store checks the culture cookie (if enabled), the saved guest choice, and the serialized server locale, in that order. If none matches, it checks the browser language if detection is enabled, then uses the default. onChange(tag) receives the matched tag after a user-initiated change, so apps can save it to a profile.
Change the regional format
Section titled “Change the regional format”The regional format controls dates and numbers independently of the UI language. Call useLocale()?.setFormatLocale?.('nb-NO') to change it, or setFormatLocale(undefined) to follow the UI language again. An invalid tag is ignored. Pass formatStorageKey to createLocale to remember the choice in local storage. The format is not synchronized across tabs and is never written to the culture cookie, so the server’s formatting is unaffected. Components follows the format through ArcComponentsProvider. Changing it refreshes locale-scoped queries like a language change does.
Keep client and server languages aligned
Section titled “Keep client and server languages aligned”In development, Arc logs a warning in two cases:
setLocaleis called with a tag that is not in the supported list. The selection does not change.- A command, query or polling response carries a
Content-Languagethat does not match the singleAccept-Languagetag the request sent. A regional variant of the request, such asnb-NOfornb, matches. Each mismatch is logged once.
Fix a mismatch by using the same languages in the server’s SupportedUICultures and DefaultUICulture and in the client’s supported list. Development means a bundler that defines import.meta.env.DEV, such as Vite and Vitest. Production builds stay silent. Native EventSource and WebSocket handshakes expose no response headers and aren’t checked.
Names across layers
Section titled “Names across layers”| Layer | UI language | Regional format |
|---|---|---|
| TypeScript | locale, setLocale |
formatLocale, setFormatLocale |
| .NET | SupportedUICultures, DefaultUICulture |
FormattingCulture, fixed per host |
| Wire | Accept-Language request, Content-Language reply, _cratisUiCulture on stream handshakes, uic in the culture cookie |
None |
Translate Cratis Components
Section titled “Translate Cratis Components”Inside <Arc locale>, use the end-to-end recipe. Without it, once cratis-l10n build has generated the loaders, register packLoaders.components in its own catalog registry, and pass the translator for the active UI language as value.catalog on CratisComponentsProvider:
import { createCatalogRegistry } from '@cratis/arc/localization/catalog';import { CratisComponentsProvider } from '@cratis/components';import { packLoaders } from './generated/localization-loaders';
const componentsCatalogs = createCatalogRegistry({ default: 'en', catalog: [packLoaders.components],});const locale = 'nb-NO';const catalog = await componentsCatalogs.load(locale);
export function LocalizedApp() { return ( <CratisComponentsProvider value={{ locale, catalog }}> <App /> </CratisComponentsProvider> );}A regional tag such as nb-NO can use the nb pack. When the UI language changes, load the translator for the new tag and pass both the tag and translator to the provider. Components uses its English text for any message not supplied by the catalog.
Hydrate a server-rendered language
Section titled “Hydrate a server-rendered language”Create a fresh store for each request. In cookie mode, supply the raw Cookie and Accept-Language headers. Arc tries .AspNetCore.Culture before Accept-Language and ignores a malformed, repeated, or unsupported cookie. Client changes write the selected tag to .AspNetCore.Culture with Path=/, SameSite=Lax, a one-year lifetime, and Secure on HTTPS. Send cookie-varying pages with Cache-Control: no-store, private and an appropriate Vary header.
// On the server, before rendering <Arc locale={serverLocale}>.const options = { supported: ['en', 'nb'], cookie: true, detectBrowserLanguage: true };const serverLocale = createLocale({ ...options, request: { cookieHeader, acceptLanguage } });await serverLocale.ready;const snapshot = JSON.stringify(serverLocale.getServerSnapshot());
// In the browser, before hydrating <Arc locale={clientLocale}>.const clientLocale = createLocale({ ...options, hydration: JSON.parse(snapshot) });await clientLocale.ready;Transfer the serialized snapshot using your framework’s safe hydration data mechanism. Use the same supported languages and catalog configuration on both sides. Hydration uses the server locale for the initial markup. After hydration, any supported app or saved choice takes priority; the server locale still wins over client detection.
Fetch paths automatically use the active language unless a callback overrides it. Native stream handshakes use a locale hint instead of a custom header; see observable transports and the header callback.
Keep command feedback current
Section titled “Keep command feedback current”CommandForm formats retained validation results against the current Arc root. Set validationDescriptors on the form or CommandFormDefaults to map application descriptors to IDs in that root’s catalogs. When the language changes, framework feedback is reformatted, including replies to submissions sent before the change. Switching language does not clear errors, reset inputs, validate the form, or submit it again.
For dialogs and toasts, keep the command result in React or MVVM state and render CommandFeedback from @cratis/arc.react/commands inside the localized root. Pass the same descriptor mappings and supply the same field titles via fieldContext if the feedback should match the form’s field wording. The component announces a localized summary separately from any preserved foreign-language detail. For custom rendering, use useCommandFeedbackFormatter(descriptors), not result.message; it subscribes to the locale and returns the display text and optional language tag.
Built-in fields and summaries apply the lang attribute to foreign-language text. Custom fieldContainerComponent or errorDisplayComponent implementations receive errorLanguage; apply it to the error text, not the surrounding form controls. A custom validationSummaryComponent can use feedback and refusalSummary when supplied to separate the localized introduction from language-tagged details.
Localize authored failures
Section titled “Localize authored failures”Use a full application catalog ID when an authored validation refusal needs to be rendered in the current UI language. The server keeps fallback prose in Message and the rule’s identity in Reason and ReasonDetail; see Localize authored failures on the server for the C# side.
Register flat catalog entries with the same IDs on both sides of a language switch:
import { createCatalogRegistry } from '@cratis/arc/localization/catalog';
export const feedbackCatalog = createCatalogRegistry({ default: 'en', catalog: [{ en: () => ({ 'booking.seatsRemaining': '{count, number} seats remain.', 'storage.temporarilyUnavailable': 'Storage is busy. Try again in {seconds, number} seconds.', }), nb: () => ({ 'booking.seatsRemaining': '{count, number} seter igjen.', 'storage.temporarilyUnavailable': 'Lagringen er opptatt. Prøv igjen om {seconds, number} sekunder.', }), }],});Pass the registry as catalogRegistry to createLocale. CommandForm, CommandFeedback, and useCommandFeedbackFormatter can render an authored rule ID with its supplied arguments. If it cannot be resolved, the formatter uses the existing validationDescriptors, built-in copy, or original prose with its language attribution, as applicable. Built-in validation and diagnostic reasons keep their existing behavior. The ID is for display; do not branch on it. Authors own ID stability, public-safe arguments, and fallback prose. Older clients continue to display the fallback without using the ID.
A public exception response mapper can supply a separate descriptor for a recognized exception. Command feedback uses it only when the catalog can format it; otherwise it shows the existing generic failure text. An explicit CommandForm exceptionMessage still overrides both. The ID doesn’t change the status, validation rules, or errorCode.
For a retained query result, use the same selector without displaying exception messages. Call it inside a component that subscribes to the current locale and pass the surface’s existing safe fallback for a query failure:
import { formatMappedFailureFeedback } from '@cratis/arc/localization/catalog';import type { IQueryResult } from '@cratis/arc/queries';import { useLocale } from '@cratis/arc.react';
export function QueryError({ result, fallback }: { result: IQueryResult<unknown>; fallback: string }) { const locale = useLocale(); const feedback = formatMappedFailureFeedback(locale, result); return <p role="alert" lang={feedback?.lang}>{feedback?.text ?? fallback}</p>;}Render this for the ordinary query failure state; keep authorization, retryable, and not-ready states on their existing paths. The selector works with ordinary HTTP query results and structured observable failure envelopes. Unhandled exceptions and unstructured transport failures do not carry a descriptor. MCP and React Suspense do not expose the descriptor through their existing error surfaces.