> [Agent navigation index](/llms.txt)

# Set up translations

Configure strict translation keys, server dictionary loading, locale resolution, fallback behavior,
and missing-message reporting.

## Define the browser-safe contract

Start with a finite set of keys. For a small application, an authored union is enough:

`src/translation-keys.ts`

```ts
export type TranslationKey = "general.ctaSearch" | "general.points" | "search.title";

```

For a larger catalogue, generate this union from your message source as part of your application
workflow. The filename is your choice; Brix neither prescribes nor generates it.

Add the translation definition and hooks to the generated `src/brix.ts`:

`src/brix.ts`

```ts
import { defineBrix } from "brix/contracts";
import { createTranslationHooks } from "brix/hooks";
import { defineTranslations } from "brix/translations";
import type { TranslationKey } from "./translation-keys.ts";

const translations = defineTranslations<TranslationKey>({ fallbackLocale: "en-GB" });

export const brix = defineBrix({
  locales: ["sv", "en-GB"] as const,
  defaultLocale: "sv",
  translations,
});

export const { useLocale, useTranslate } = createTranslationHooks(translations);

export const {
  createApiContract,
  createMarkdownIndexContract,
  createPageContract,
  createResponseContract,
  executeApi,
  getMarkdownIndexPath,
  getPath,
} = brix;

```

A translated application must list at least one locale and set `defaultLocale`; there is no built-in
default. `defaultLocale` and `fallbackLocale` must both be configured locales, and locales must be
unique. `defineBrix` throws at startup when any of these rules is broken.

Keep the key union strict. `defineTranslations<string>` is a type error because Brix cannot verify or
filter arbitrary keys for the browser.

## Load dictionaries on the server

Keep dictionaries in a server-only module. This example deliberately omits a Swedish message to
demonstrate fallback to English:

`src/translations.server.ts`

```ts
import type { TranslationKey } from "./translation-keys.ts";

export const dictionaries = {
  sv: { "general.ctaSearch": "Sök", "search.title": "Sök" },
  "en-GB": {
    "general.ctaSearch": "Search",
    "general.points": "{points} points",
    "search.title": "Search",
  },
} satisfies Record<"sv" | "en-GB", Partial<Record<TranslationKey, string>>>;

```

Pass a `translations.load` callback to `defineBrixServer` and export the request accessors:

`src/brix.server.ts`

```ts
"use server";

import { defineBrixServer } from "brix/server";
import { brix } from "./brix.ts";
import { env } from "./env.server.ts";
import { dictionaries } from "./translations.server.ts";

export const brixServer = defineBrixServer(brix, {
  env,
  translations: {
    load: (_c, { locale }) => dictionaries[locale],
  },
});

export const {
  createApiRoute,
  createFragment,
  createMarkdownIndexRoute,
  createPageRoute,
  createResponseRoute,
  getLocale,
  getTranslator,
} = brixServer;

```

`translations` is required when `defineBrix` has translations, and rejected when it does not. The
loader receives the request context and `{ locale }` and returns a partial string dictionary, or a
promise of one, for any configured locale. Brix:

- rejects a result that is not an object or contains a non-string value, which fails the request;
- freezes the validated dictionary and loads each locale at most once per request, sharing it across handlers, page rendering, fragments, and Markdown;
- retries a rejected load if the same request asks for a translator again;
- does not cache dictionaries across requests.

At this point, a component that translates `general.ctaSearch` renders **Sök** for Swedish requests.
Looking up `general.points` on that request falls back to **{points} points** from `en-GB`. This
checked-in dictionary is the recommended starting point; add remote loading only when messages must
be published independently of the application.

## Load remote dictionaries when needed

Brix adds no translation cache, and `executeApi` does not cache a request merely because the
translation loader makes it. Configure caching explicitly at the call site:

`src/data-cache.server.ts`

```ts
import { createDataCache, createMemoryDataCacheStore } from "brix/cache";

export const dataCache = createDataCache({
  namespace: "booking-web-development",
  store: createMemoryDataCacheStore(),
});

```

`src/brix.server.ts`

```ts
"use server";

import { defineBrixServer } from "brix/server";
import { brix, executeApi } from "./brix.ts";
import { dataCache } from "./data-cache.server.ts";
import { env } from "./env.server.ts";
import { getDictionaryApiContract } from "./generated/translations-api.ts";

export const brixServer = defineBrixServer(brix, {
  env,
  translations: {
    load: (_c, { locale }) =>
      executeApi(getDictionaryApiContract, {
        baseUrl: "https://translations.example.com",
        query: { locale },
        cache: dataCache.public({ ttl: "1h", staleIfError: "1d" }),
      }).unwrap(),
  },
});

```

`getDictionaryApiContract` is an application GET contract whose response is a partial string
dictionary; replace the example origin and namespace. This loader opts into a one-hour public cache
and permits stale data for one day when a refresh fails. Without the `cache` option, every request
performs the read. Retries are likewise opt-in through the client's own options.

Keep the cache in a separate server-only module that does not import `brixServer`, avoiding a circular
initialization dependency. Invalidate the contract after publishing new messages. A process-memory
store is local to one process; use a shared store when instances must reuse entries. A loader failure
fails the request unless the data cache can serve eligible stale data. See
[data caching](/docs/caching.md) before choosing public or private partitions, a production store, or
invalidation guarantees.

## Resolve locale consistently

Brix finalizes one locale per request and uses it for `getLocale(c)`, `useLocale()`, `<html lang>`,
the `Content-Language` header, SSR, Markdown, hydration, and the dictionaries it loads. It picks the
first rule that applies:

1. A registered fragment request with a valid `__brix_locale` query uses that locale.
1. A localized page path used by exactly one locale uses that locale.
1. Otherwise Brix calls your optional `resolveLocale(c)`. A configured locale wins, unless the page path is shared by several locales that do not include it. Returning `undefined` defers to the next rule. Returning an unconfigured locale throws and fails the request.
1. Otherwise Brix uses `defaultLocale`, or, when a shared page path does not include it, the first of that path's locales in `locales` order.

API routes and other unlocalized routes always reach `resolveLocale`, so keep it cheap. It runs before
`defineBrixServer` middleware and route authentication: it cannot read a user that those later
callbacks set, and Brix does not reselect the locale after authentication. Page loaders run later and
can read the authenticated user, but cannot change the finalized locale.

For a session preference, share one request-memoized lookup rather than invoking authentication
inside the locale resolver or loading the session twice. This example assumes application-owned
`sessions.user(request)` returns `Promise<User | null>` and that `User.locale` is a configured locale:

`src/brix.server.ts`

```ts
"use server";

import type { Context } from "brix/hono";
import { defineBrixAuth, defineBrixServer } from "brix/server";
import { brix } from "./brix.ts";
import { env } from "./env.server.ts";
import { sessions, type User } from "./sessions.server.ts";
import { dictionaries } from "./translations.server.ts";

type AuthContext = Context<{ Variables: { user: User } }>;
const sessionRequests = new WeakMap<Request, Promise<User | null>>();
function getSession(request: Request): Promise<User | null> {
  let pending = sessionRequests.get(request);
  if (!pending) {
    pending = sessions.user(request);
    sessionRequests.set(request, pending);
  }
  return pending;
}

const auth = defineBrixAuth<AuthContext>(async (c, next, redirectUrl) => {
  const user = await getSession(c.req.raw);
  if (!user) {
    return redirectUrl ? c.redirect(redirectUrl) : c.json({ error: "Unauthorized" }, 401);
  }
  c.set("user", user);
  await next();
});

export const brixServer = defineBrixServer(brix, {
  env,
  auth,
  resolveLocale: async (c) => (await getSession(c.req.raw))?.locale,
  translations: {
    load: (_c, { locale }) => dictionaries[locale],
  },
});

```

The weak map shares a promise only for the same raw request object, never by URL or across users,
and does not keep completed requests alive. Move the helper into your session module when several
server bindings need it. `resolveLocale` and the translation callbacks receive a narrower context type
than route handlers and loaders, which `createService` accessors do not accept; do not cast the
context to reach them. Keep the session lookup free of authorization redirects. Selecting a locale never grants
access: routes still opt into `auth`. A session-derived locale is invisible to shared edge caches, so
keep personalized output uncached unless your edge guarantees isolation independently.

Brix carries the resolved locale to deferred fragments in the reserved `__brix_locale` query
parameter, so fragment schemas must not declare it. Registered fragment GET and HEAD endpoints apply
it before application middleware runs, so middleware that calls `getTranslator(c)` receives the
fragment's dictionary rather than the default. A value that is repeated or not one of the fragment's
locales returns 400 before application middleware. Ordinary routes and unknown fragment paths ignore
this parameter.

## Choose fallback behavior

When the active locale differs from `fallbackLocale`, Brix also loads the fallback dictionary. Set
`fallback: false` to disable it, or pass a callback that receives the context and
`{ locale, fallbackLocale }` and returns, or resolves to, a boolean. Use either only for a deliberate
alternate policy.

Every translator, on the server and in the browser, looks a key up in this order:

1. the active locale's message;
1. the fallback message, when fallback is enabled;
1. the optional second argument, `translate(key, example)`, returned unchanged in production builds and as `HC: example` in development so untranslated text stands out;
1. the key itself.

The example does not widen the key union: it covers a key your application already declares but
whose message has not been published yet. An empty string is a valid message, not a missing one.
Messages are returned unchanged, including braces, Unicode, newlines, and HTML-looking text.

Islands receive the active messages with fallback messages already merged in, filtered to the keys
they use.

## Report missing messages

A lookup that reaches step 3 or 4 counts as missing. Configure `onMissing` to collect misses from
server translators and SSR components:

`src/brix.server.ts`

```ts
translations: {
  load: (_c, { locale }) => dictionaries[locale],
  missingTimeoutMs: 250,
  onMissing: ({ keys, locale, method, path, requestId }) => {
    console.warn("Missing translations", { keys, locale, method, path, requestId });
  },
},

```

The callback runs at most once per request, after the route and application middleware finish, and only when
that request had misses. Its `TranslationMissingEvent` (exported by `brix/server`) contains:

- `keys`: the deduplicated missing keys, sorted;
- `locale`: the request's active locale;
- `method` and `path`: the request method and pathname, without the query string;
- `requestId`: the Brix request ID, also sent in the `x-request-id` response header.

Where the platform's execution context provides `waitUntil` (Cloudflare Workers and Fastly
Compute), the callback runs after the response is sent. On Node and AWS Lambda the response waits
for it, so it adds latency to those requests. `missingTimeoutMs` bounds the wait and defaults to `1000`; a
negative or non-finite value uses the default, and a value above `2147483647` (the largest timer
delay) waits that long. A thrown error, rejection, or timeout is logged with
`console.error` and never changes the response. Keep the callback fast: enqueue telemetry rather
than awaiting a remote write.

Lookups in the browser after hydration do not reach `onMissing`. Without an `onMissing` prop, the
Preact and React providers warn once per locale and key in development browsers and stay silent in
production builds.

Continue with [translate and test application output](/docs/translations-usage.md).
