Translate and test application output
Translate components, server code, and semantic Markdown while preserving hydration and cache boundaries, then test each runtime. This guide assumes the contract and loader from setting up translations.
Translate components
#import { useTranslate } from "#brix";
export function SearchButton() {
const translate = useTranslate();
return <button type="submit">{translate("general.ctaSearch")}</button>;
}
The same hook works in SSR components and islands. useLocale() returns the request's resolved
locale. Both hooks throw outside a translation provider; Brix installs one for every rendered page
and fragment.
Brix statically analyzes translation usage so that it can send each hydration root only the messages its islands use. Follow these rules:
- import
useTranslateanduseLocaleby name with a static import from#brix(a static path import ofsrc/brix.ts, such as#/brix.ts, is analyzed the same way); - assign
useTranslate()directly to one local variable and call that variable directly; - pass string-literal keys only.
Namespace, default, or dynamic imports of the hooks, aliased or passed translators, and variable,
template, or conditional key arguments fail brix check and brix build, because the build could not
determine which messages the component needs. Both commands analyze the same production sources:
tests (*.test.*, *.spec.*, *.test-d.ts, src/test/, __tests__/), stories, and
declarations are skipped, so a test may call a translator with a variable key. Only references to
the translator or hooks count: object keys and member names that happen to share their names, such
as style={{ translate: "0 -2px" }} or context.translate(10, 10), are unaffected. For
conditional text, branch around complete calls:
const label = searching ? translate("search.title") : translate("general.ctaSearch");
Each page or fragment hydration root receives the union of messages reachable from its islands, shared by those islands rather than duplicated per instance. Keys used only by SSR components are not sent to the browser, and a page without translating islands sends no dictionary payload. Contentful Live Preview receives the messages its adapters use in the same way.
Once an application uses translations, every module in an island's browser graph must have dynamic
imports the bundler can follow. brix build rejects a runtime-computed specifier such as
import(widgetUrl) or import(`date-fns/locale/${code}`) in an island graph, even when that
island translates nothing, because the payload could miss messages used by the module it loads.
brix check and the development server cannot see the production island graph, so only the build
reports it. Use one of these forms instead:
- a static specifier, such as
import("./MapWidget.tsx"); - a relative template that Vite expands to known modules, such as
import(`./locales/${code}.ts`); import(/* @vite-ignore */ sdkUrl)for a module outside the application bundle, such as a vendor SDK URL. That module cannot use the application's translation hooks.
Interpolation is explicit application code:
translate("general.points").replace("{points}", formatPoints(points));
Here formatPoints is your own formatter. See fallback behavior
for what a lookup returns when a message is missing, including the optional example text in
translate(key, example).
Translate server code
#Route handlers, page loaders, and middleware await the request translator from #brix/server. It
shares the request-local dictionaries that SSR uses, so repeated calls do not reload them. Inside any
of those callbacks, with its context c:
const translate = await getTranslator(c);
const title = translate("search.title");
const locale = getLocale(c);
Use this in loaders to translate data before it reaches components or Markdown.
Translate semantic Markdown
#Markdown callbacks are server code. Do not call hooks there, and never derive Markdown from rendered HTML. This localized search page renders the same message as HTML and Markdown:
import { createPageContract } from "#brix";
export const searchPageContract = createPageContract({
path: { sv: "/sok", "en-GB": "/search" },
representations: ["markdown"],
});
import { useTranslate } from "#brix";
export function SearchPage() {
const translate = useTranslate();
return (
<main>
<h1>{translate("search.title")}</h1>
</main>
);
}
import { md } from "brix/markdown";
import { createPageRoute, getTranslator } from "#brix/server";
import { SearchPage } from "./Page.tsx";
import { searchPageContract } from "./contract.ts";
export const searchPageRoute = createPageRoute(searchPageContract, {
component: SearchPage,
markdown: async (c) => {
const translate = await getTranslator(c);
return md.document({
body: md.heading(1, md.text(translate("search.title"))),
});
},
});
The negotiated response and the durable .md alias use the same resolved locale and
Content-Language. Markdown bypasses the Preact provider and hydration payloads; Markdown index
callbacks translate the same way. See semantic Markdown pages.
Keep edge caches locale-safe
#In a translated application, the edge must be able to see every input that selects the locale before it may share a cached page or fragment. A page path used by exactly one locale already identifies it, so those pages are partitioned by path automatically. If the host name determines the locale, declare it so that pages with shared or unlocalized paths, and fragments, can be cached per host:
translations: {
load: (_c, { locale }) => dictionaries[locale],
localePartition: "host",
},
Otherwise the locale is opaque to the edge: it may come from a cookie, header, or session. The
brix/edge cache decisions then bypass shared caching for those pages and fragments rather than risk
serving one locale's response to another. The exception is a deferred fragment URL that carries a
valid __brix_locale query parameter; the edge manifest lists each fragment's finite locale values so
shared caches can partition them.
Fragment hydration carries only that fragment's statically used messages, and independently cached fragments follow the same partition rules. See fragments and caching.
Use Contentful as a source
#The loader accepts a partial string dictionary regardless of where messages originate. If your content pipeline publishes dictionaries from Contentful, consume them through an API-backed loader and derive the key union from the same naming scheme. Components receive strings, not Contentful entries.
Flattening typed Contentful Entry.fields directly inside a translation loader is rejected by the
managed entry-boundary checks: only conventional rendering adapters may inspect entries, and those
produce UI and Markdown, not dictionaries. Renaming a dictionary helper to an adapter file is not a
supported workaround. Use checked-in dictionaries or a dictionary API until your source integration
meets that boundary. See Contentful.
Translate outside a request
#Scripts, queue consumers, and unit tests of formatting helpers have no request translator. Build one
from dictionaries you already hold with createTranslator from brix/translations:
import { createTranslator } from "brix/translations";
import type { TranslationKey } from "#/translation-keys.ts";
import { dictionaries } from "#/translations.server.ts";
const translate = createTranslator<TranslationKey>({
active: dictionaries.sv,
fallback: dictionaries["en-GB"],
isProduction: true,
onMissing: (key) => console.warn(`Missing translation: ${key}`),
});
It applies the same lookup order as request translators. It does not call your loader, validate the
dictionaries, or report to the server onMissing callback; pass its own onMissing when you need to
observe misses. isProduction: false enables the HC: prefix for example text.
Test each runtime
#Route tests supply dictionaries instead of invoking the production loader. A locale missing from
translations loads as an empty dictionary. Use a different message for each locale and assert both
the text and Content-Language, so a default-locale leak cannot pass:
import { expect, it } from "brix/test";
import { testPage } from "#brix/test";
import { searchPageRoute } from "./route.ts";
it("renders Swedish Markdown", async () => {
const response = await testPage(searchPageRoute, {
locale: "sv",
representation: "markdown",
translations: {
sv: { "search.title": "Sök" },
"en-GB": { "search.title": "Search" },
},
});
expect(response.markdown).toContain("Sök");
expect(response.headers.get("Content-Language")).toBe("sv");
});
testApi, testFragment, and testResponse accept the same translations option. Cover an active message, a
fallback-only message, a missing key with and without example text, and an empty-string message.
Browser component tests mount the production provider with renderWithTranslations from
brix/test/browser:
import { expect, it } from "brix/test";
import { renderWithTranslations } from "brix/test/browser";
import { SearchButton } from "./SearchButton.tsx";
it("labels the search button", async () => {
const screen = await renderWithTranslations(<SearchButton />, {
locale: "sv",
messages: { "general.ctaSearch": "Sök" },
});
await expect.element(screen.getByRole("button", { name: "Sök" })).toBeVisible();
});
messages is the complete dictionary for that render; no fallback dictionary is merged in. Storybook
previews use createBrixTranslationPreview from brix/storybook/test, which adds the provider and a
locale toolbar without a server loader. See testing components,
route tests, and Storybook stories.
Island and Storybook renders receive translations from Brix. If you mount the Preact
TranslationProvider from brix/hooks yourself, pass both locale and dictionary; it throws
without them instead of rendering untranslated keys.
Managed React applications use TranslationProvider and createTranslationHooks from
@brix/react; see managed React. Authors of other UI bindings can build a
provider and hooks with the same lookup and missing-key reporting through createTranslationBindings
from brix/hooks/adapter; applications do not import that subpath.