---
title: Localization in Arc clients
editUrl: https://github.com/Cratis/Arc/edit/main/Documentation/frontend/core/localization.md
description: Use @cratis/arc/localization/catalog for ICU message catalogs. Use @cratis/arc/localization for the locale store, literal-tree translations, and command…
lastUpdated: 2026-12-06T00:00:00.000Z
---

Use `@cratis/arc/localization/catalog` for ICU message catalogs. Use `@cratis/arc/localization` for the locale store, literal-tree translations, and command feedback without loading ICU. Neither entry point depends on React.

## Format command feedback with catalogs

Create one catalog registry for the application root. A bare dictionary registers app English; tag entries can load partial catalogs on demand. Enable TypeScript `resolveJsonModule` to import the JSON directly.

```typescript
import { createCatalogRegistry, createValidationFormatter } from '@cratis/arc/localization/catalog';
import en from './messages.en.json';

const registry = createCatalogRegistry({
    default: 'en',
    catalog: [en, { fr: () => import('./locales/fr/validation.json') }],
});
const translator = await registry.load('fr-CA');
const formatter = createValidationFormatter(translator, {
    'constraintViolation/UniqueHours': 'app.hours.duplicate',
});
```

Use `formatter.formatValidationResult` and `formatter.formatCommandResult` for string-only consumers. Both use the same descriptor, rather than matching the server's English text. Pass a field title to `formatValidationResult` to prefer it over the field name. An optional `messageArguments` payload supplies named scalar values; unmapped application-authored messages are shown as written. Known framework failures fall back to generic copy rather than displaying internal diagnostics.

Command execution and server validation keep the original descriptor, arguments, field paths, and message. `replyLanguage` on `CommandResult` and its validation results comes from `Content-Language` and is absent if the header is unavailable. There is no reply language for client-generated feedback. For cross-origin commands, expose `Content-Language` to the browser if your transport or proxy would otherwise hide it.

Use `createFeedbackFormatter(store.getSnapshot(), descriptors)` to get `{ text, lang? }` feedback for rendering. A language tag is supplied on authored detail when its language differs from the snapshot. Render that text as text, not HTML, and use `lang` on the element that contains it. When presenting feedback in a live region, introduce foreign-language detail with `formatter.refusalSummary` separately from the tagged detail. Create a new formatter from the current snapshot when the locale changes; reuse the result, not the previous formatted strings.

Catalog files contain flat, full message IDs, such as `arc.validation.requiredField` from Arc's `validation` namespace and `arc.commands.failed` from the `commands` namespace. Values are plain ICU MessageFormat 1 strings such as `"{field} is required."`. Plurals use the language of the matching catalog. For each key, the registry checks the selected tag, its parents, the app default and its parents, and English. At a given tag, an app dictionary wins over pack copy. A failed loader rejects `load` without changing previously loaded translators; retry by calling `load` again.

### Register an external pack

An `ArcCatalogPack` provides `messages` and a `manifest` containing `product: '@cratis/arc'`, a canonical `locale`, `catalogFormat: 'icu-mf1'`, a `coreRange` such as `>=1.2.0 <1.3.0`, a `sourceTemplateRevision`, and `coverage: 'complete'` or `'partial'`. Register the pack directly in `catalog` or through a loader keyed by its locale. Arc compares the declared range with its package's major and minor version before using the catalog. Prereleases use the same minor line as the corresponding stable release. A malformed pack or incompatible range reports an error and is ignored. A template revision mismatch reports a warning and still registers the pack if it is compatible. Use `onDiagnostic` to receive these diagnostics instead of writing them to the console.

### Register Norwegian Bokmål

Install `@cratis/arc.locale.nb` at the same version as `@cratis/arc`, then register it under `nb`. The module exports the catalog as its default export and a named `manifest`. Pass both to the registry so Arc can check compatibility.

```typescript
import { createCatalogRegistry, createValidationFormatter } from '@cratis/arc/localization/catalog';

const registry = createCatalogRegistry({
    default: 'en',
    catalog: [{
        nb: async () => {
            const { default: messages, manifest } = await import('@cratis/arc.locale.nb');
            return { messages, manifest };
        },
    }],
});
const formatter = createValidationFormatter(await registry.load('nb-NO'));
```

`nb-NO` falls back to its parent `nb`. Without the pack, Arc-owned messages use the built-in English catalog. The deprecated `formatValidationResult(result, locale, context)` from `@cratis/arc/localization` retains its original English and Bokmål copy and warns once on use of its built-in Bokmål. Use `createValidationFormatter` and register non-English catalogs explicitly for new applications.

`Cratis.Arc.Locale.Nb` is the reserved NuGet name, not a published or planned server catalog for this release. Servers continue to send English feedback and descriptors; the client supplies the localized text.

## Generate catalog loaders for an app

Use `cratis-l10n`, the npm executable included in `@cratis/arc`, to generate lazy catalog imports instead of maintaining them by hand. The CLI and Vite `localization()` plugin require Node.js 22.15 or later on the 22.x line, 23.5 or later on the 23.x line, or Node.js 24 and later. This requirement applies only to the localization tooling, not the browser runtime.

Put `localization.json` in the app root and declare the supported languages and default. The optional `$schema` points to the JSON Schema shipped with `@cratis/arc`; adjust the path if the policy isn't beside `node_modules`.

```json
{
    "$schema": "./node_modules/@cratis/arc/dist/localization/schema.json",
    "languages": ["en", "fr"],
    "default": "en",
    "aliases": { "fr-CA": "fr" }
}
```

Optional `aliases` map requested base tags to supported languages. Matching is case-insensitive, and an exactly supported tag takes precedence over an alias.

| File | Purpose |
| --- | --- |
| `Features/Hours/Register/messages.en.json` | Author English next to the feature. Use a flat map of full IDs to ICU MessageFormat 1 strings, such as `{"app.hours.title":"Hours"}`. |
| `Shell/messages.en.json` | Author shared `app.common.*` messages. |
| `locales/fr/hours.json` | Translate `app.hours.*` IDs. The second segment of the ID determines the filename. Use canonical language tags for directories, for example `pt-BR`. |
| `locales/fr/overrides.json` | Optionally override a subset of `arc.*` and `components.*` messages. |
| `locales/en/hours.json` | Exchange English templates with translators. Only `export` writes these files. The app always loads English from the slice files instead. |
| `generated/` | Generated TypeScript. Keep this directory out of version control. Set `generatedDir` in `localization.json` to a different project-relative output directory if needed. |

Run the commands from the app root, or pass `--root <dir>` to select a different app. Use `cratis-l10n --help` for usage.

- `cratis-l10n build` generates `localization-types.ts` (`MessageId` and `MessageParameters`), `messages.ts` ([typed message accessors](#call-messages-through-typed-accessors)) and `localization-loaders.ts`. The loaders module also exports `localizationPolicy` for `createLocale(localizationPolicy)`. If several slice files contribute to one feature, a generated `localization-feature-<feature>.ts` module groups them behind one lazy entry.
- `cratis-l10n add fr` adds a language and fills in missing keys with English. It leaves existing translations in place. For partial translations, omit keys that should use the runtime's fallback. Adding `nb` or `nb-NO` also adds and reports a `no` alias to the added language unless `no` is already supported or has an alias.
- `cratis-l10n export` writes the English exchange templates and their content revision in `locales/en/.revision.json`. Rerun it after changing English copy or IDs before sending the templates to translators.
- `cratis-l10n check` checks IDs, ICU syntax, placeholder names and types, and coverage against the available English templates. Missing entries in partial catalogs and stale template revisions are warnings. The check also warns when Bokmål is supported and `no` is neither supported nor aliased. Exit codes are `0` for success (including warnings), `1` for validation errors, and `2` for usage or I/O errors.
- `cratis-l10n check --server path/to/appsettings.json` also compares the frontend policy with `Cratis:Arc:Localization` in that JSON file. The path is relative to the working directory. Comments, trailing commas, and colon-separated configuration keys are accepted. Each frontend language must have one match on the server, the defaults must match in both directions, and each frontend alias must have an equivalent server alias (for example, `nb` and `nb-NO` can match). Server aliases also need a frontend counterpart unless their target has no frontend match. The check doesn't read environment overrides or change the server configuration.

### Run generation with Vite or a prebuild script

Register `localization()` in `vite.config.ts`. It generates files before building and regenerates them as you edit the source catalogs, translations, or language configuration in dev.

```typescript
import { localization } from '@cratis/arc.vite';
import { defineConfig } from 'vite';

export default defineConfig({ plugins: [localization()] });
```

The plugin uses the Vite root by default. If `localization.json` and your catalogs live one directory above it, use `localization({ root: '..' })` to generate and watch from that directory instead. Relative paths are resolved against the Vite root.

Without Vite, add the following scripts to `package.json` and run `check:l10n` in CI. Use a bundler that supports literal dynamic JSON imports and enable TypeScript `resolveJsonModule`.

```json
{
    "scripts": {
        "prebuild": "cratis-l10n build",
        "check:l10n": "cratis-l10n check"
    }
}
```

### Load the open route's catalog

Register a route's feature map, not the entire generated map. The registry loads the configured language and its fallbacks without requesting catalogs for unopened routes. Enable `resolveJsonModule` for the generated catalog imports.

```typescript
import { createCatalogRegistry } from '@cratis/arc/localization/catalog';
import { catalogLoaders, localizationPolicy, overrideLoaders, packLoaders } from './generated/localization-loaders';

const hours = createCatalogRegistry({
    default: localizationPolicy.defaultLocale,
    catalog: [packLoaders.arc, overrideLoaders, catalogLoaders.hours],
});
const translator = await hours.load('fr');
const title = translator.t('app.hours.title');
```

`packLoaders` groups optional platform packs by product. The generator adds a pack only if its name matches `@cratis/arc.locale.<tag>` or `@cratis/components.locale.<tag>`, it is installed and listed in the app's `dependencies`, and the tag is a configured language or its parent. Missing packs are reported as English fallback; the tooling never installs them.

Arc packs keep their manifests for runtime validation. For Components packs, the generator checks the installed `@cratis/components` version against the pack's declared range. It warns and omits the loader if it cannot confirm compatibility. Rerun generation after updating Components or its packs. Register `packLoaders.components` in a [separate Components catalog](/arc/frontend/react/localization/#translate-cratis-components).

### Call messages through typed accessors

`generated/messages.ts` has one function per message and an `m` object that groups them by the ID's path below `app`. Use them where the ID is known when you write the code, to get completion, go-to-definition and find-usages. Keep `t(id, values)` for IDs that are only known at runtime.

```typescript
import { Globals } from '@cratis/arc';
import { createLocale } from '@cratis/arc/localization';
import { createCatalogRegistry } from '@cratis/arc/localization/catalog';
import { catalogLoaders, localizationPolicy } from './generated/localization-loaders';
import { m } from './generated/messages';

const locale = createLocale({
    ...localizationPolicy,
    catalogRegistry: createCatalogRegistry({ default: localizationPolicy.defaultLocale, catalog: [catalogLoaders.hours] }),
});
Globals.locale = locale;
await locale.ready;

const title = m.hours.title();                              // 'app.hours.title'
const people = m.hours.people({ count: 2, team: 'Arc' });   // 'app.hours.people'
const sameAsT = locale.t('app.hours.people', { count: 2, team: 'Arc' });
```

A message without placeholders takes no argument. A message with placeholders takes one required object with the same types as `MessageParameters`: `number` for `plural`, `selectordinal`, `number`, `date` and `time` (pass dates as epoch milliseconds), `string` for `select`, and `string | number | boolean` for a plain placeholder. An unknown key, a missing value, an extra value and a value of the wrong type are compile errors, whether you pass the values inline or through a variable.

Each call formats through `Globals.locale`, the shared locale store for browser clients, so it uses the same catalogs and the same fallback chain as `t()` and returns the new language after `setLanguage()` resolves. The store's `catalogRegistry` must include the catalogs of the messages you call. An accessor returns the message ID if no store is set, the catalogs have not loaded yet, or no catalog can render the message. Because `Globals.locale` is shared by the whole process, don't use the accessors in a server that renders for several users; use the request's own store and its `t` there.

The module depends only on `@cratis/arc`, not on React. To let a bundler drop unused messages, import the functions by name instead of `m`: `import { hours_title } from './generated/messages'`.

`m` and its groups hold only the accessors. They have no prototype, so `m.hours.toString` is `undefined` and a compile error unless a message has that ID.

| Message ID | Function | Through `m` |
| --- | --- | --- |
| `app.hours.title` | `hours_title` | `m.hours.title` |
| `app.hours.list.empty` | `hours_list_empty` | `m.hours.list.empty` |
| `app.sign-in.2fa.code sent` | `sign_in__2fa_code_sent` | `m.sign_in._2fa.code_sent` |

The names come from the ID in three steps:

1. The leading `app` segment is dropped, and the remaining segments form the path in `m`.
2. In each segment, every character (Unicode code point) other than `A`–`Z`, `a`–`z`, `0`–`9`, `_` and `$` becomes `_`. If the result is empty or starts with a digit, it gets a `_` prefix. The alphabet is fixed to ASCII so that the generated names don't depend on the Node version that runs the build. Letters outside it, such as `å`, each become `_`: `app.hours.blåbær` is `m.hours.bl_b_r`.
3. The function name is the mapped segments joined with `_`.

The build fails with an error that names both IDs and their files when two IDs get the same function name (`app.hours.sign-in` and `app.hours.sign_in`, `app.hours.blå` and `app.hours.blø`, or `app.hours.list_empty` and `app.hours.list.empty`), or when one ID is a prefix of another so that a name would be both a message and a group (`app.hours.list` and `app.hours.list.empty`). Rename one of the IDs.

## Use the locale store and literal-tree translations

```typescript
import { createLocale, defineTranslations } from '@cratis/arc/localization';

export const translations = defineTranslations('en', {
    form: { name: 'Name', submit: 'Save' },
}, {
    nb: { form: { name: 'Navn', submit: 'Lagre' } },
});

export const locale = createLocale({ catalogue: translations, storageKey: 'ui-language' });

locale.setLocale('nb');
const labels = translations.forLocale(locale.getSnapshot().locale);
```

The fallback pack defines the read-only shape, including nested objects and arrays. Other packs must provide the same keys and value kinds. `forLocale()` checks the canonical tag, then its parents (for example, `nb-NO` → `nb`), and then the fallback pack.

`createLocale()` defaults to `en` (or the catalogue fallback). Pass `supported` explicitly or infer supported locales from a catalogue. `defaultLocale` selects the initial language; `fallbackLocale` defaults to the catalogue fallback or the default, and both must be supported. `formatLocale` follows the active UI locale unless you pin it separately for `Intl` formatting.

`getSnapshot()` returns `{ locale, supported, formatLocale }`, plus `t` and `tWithLocale` when a catalog registry is configured. `subscribe(listener)` returns an unsubscribe function. `setLocale(tag)` canonicalizes a supported tag and notifies listeners only when the selection changes. In development, a tag that isn't supported logs a warning and leaves the selection unchanged. If you supply `storageKey`, the store remembers the selection and listens for changes from other tabs while subscribed. Blocked storage does not prevent an in-memory switch. A valid saved selection wins over opt-in `detectBrowserLanguage: true`, then the default. `getServerSnapshot()` always returns the configured default, independent of saved browser preferences.

`setFormatLocale(tag)` changes `formatLocale` at runtime without touching the UI language. `setFormatLocale(undefined)` follows the UI language again, and an invalid tag is ignored. Supply `formatStorageKey` in the browser to remember the choice in local storage; the saved value takes precedence over `formatLocale`, and hydration snapshots ignore it. The format isn't synchronized across tabs or written to the culture cookie. `localeDirection(tag)` returns `'ltr'` or `'rtl'` for a language tag.

## Send the language to Arc

For plain clients, bind a store with `command.setRequestDefaults({ locale })` or `query.setRequestDefaults({ locale })`. You can also set `Globals.locale = locale` once at browser bootstrap to opt bare clients into a shared store. Never put a per-user locale in `Globals` on the server; create and bind a separate store per request. For React applications, pass the store to [the Arc provider](/arc/frontend/react/localization/).

Commands, query fetches, observable snapshots, polling, and SSE hub control requests read the current locale and send `Accept-Language`. Explicit values from `httpHeadersCallback` or `setHttpHeadersCallback()` replace the automatic value regardless of casing; a per-client callback wins over the configured callback. Arc retains its own reserved headers. In development, a command, query fetch or poll that sent a single `Accept-Language` tag logs one warning per mismatch when the response's `Content-Language` names an unrelated language. Set `httpHeadersCallback` on `<Arc>` or pass it to `setRequestDefaults()` to configure client defaults. Without client-scoped defaults, command execution and validation, polling, and SSE hub control requests also use `Globals.httpHeadersCallback`. Plain query fetches and observable snapshots inherit only the locale from `Globals`.

Native WebSocket and EventSource can't attach custom headers. Arc reserves `_cratisUiCulture` as the transport selector for UI culture on native stream URLs. Arc adds it only when a locale store is configured and there is a single valid tag to send. Honoring the selector requires the .NET request culture resolver. The resolver uses it only when server localization is configured and the tag is a supported culture. An explicit `Accept-Language` preference list is sent on fetch requests but isn't serialized into a stream URL. No other header is copied into stream URLs. A running observable subscription reopens for the new locale and retains its unsubscribe handle.

For jobs and reactors, `cratis-l10n build --catalog-output <file>` can instead compile a [portable catalog for Arc.Core](/arc/backend/csharp/core/localization/#render-catalog-messages-outside-http). This mode does not generate browser loaders or include installed packs.
