--- name: add-i18n version: 2.2.0 description: | Wire `@pracht/i18n`: locale detection, typed lazy dictionaries, and either locale-prefixed routes with hreflang or one URL per page with a cookie switcher. Use for "add i18n", "set up translations", "make my app multilingual", "add locale routing", "switch language without changing URLs". allowed-tools: - Bash - Read - Write - Edit - Grep - Glob - AskUserQuestion --- # Pracht Add i18n `@pracht/i18n` ships locale-detection middleware, lazy dictionaries with keys typed from the default locale, `t()`/`tPlural()` (plurals via `Intl.PluralRules`), `localePath()`, and `hreflang()` for `head()`. Full guide: — which also carries a hand-rolled fallback recipe if the user refuses the dependency. Working setups of both strategies live in : locale-prefixed (`/welcome`, `/en/welcome`, `/nl/welcome`) and prefix-free (`/greeting`, `src/api/locale.ts`). MCP: if `pracht dev-mcp` is registered, prefer its `inspect_*`, `generate_*`, `doctor`, and `verify` tools to the CLI. ## Step 1: Pick locales and a URL strategy Use `AskUserQuestion` once for the supported locales (default `en` plus one or two), the default locale, and the URL strategy: | | **A. Locale-prefixed** (`/en/about`) | **B. One URL per page** (`/about`) | | --- | --- | --- | | Use when | Public, indexable content | URLs cannot move, or the app is behind a login | | Locale from | The path | The cookie — switching needs no navigation | | Render modes | Any, including `ssg`/`isg` | `ssr`/`spa` only (`Vary: Cookie, Accept-Language`) | | hreflang | Works | Impossible — one URL cannot carry alternates | | Cost | Changes every URL | One indexed language | Never migrate a live app's URLs without saying so explicitly. Both strategies can coexist in one app. Keep the default detection order `["path", "cookie", "header"]` either way — the path source simply never matches a prefix-free route — and change it only for an explicit cookie-only or header-only request. ```bash npm install @pracht/i18n ``` ## Step 2: Instance and dictionaries ```ts // src/i18n/index.ts import { createDictionaries, defineI18n } from "@pracht/i18n"; export const i18n = defineI18n({ locales: ["en", "fr"], defaultLocale: "en" }); export type AppLocale = (typeof i18n.locales)[number]; export const dictionaries = createDictionaries( { en: () => import("./locales/en.ts"), fr: () => import("./locales/fr.ts") }, { defaultLocale: "en" }, ); ``` One dictionary module per locale — flat string keys, default export, `as const` so key typing works: ```ts // src/i18n/locales/en.ts export default { "home.title": "Welcome, {name}", "cart.items.one": "{count} item", "cart.items.other": "{count} items", } as const; ``` Plural keys declare one entry per `Intl.PluralRules` category the locale needs (`.one`, `.other`, plus `.few`/`.many` for e.g. Polish); `tPlural()` falls back to `.other`. Non-default locales may omit keys — `load()` merges the default locale underneath. ## Step 3: Detection middleware ```ts // src/middleware/i18n.ts import { i18n } from "../i18n/index.ts"; export const middleware = i18n.middleware; ``` It sets `context.locale`, persists URL-prefix choices in a `SameSite=Lax` cookie, and appends `Vary: Cookie` / `Accept-Language` for whichever sources it consulted. Persistence happens only on per-request (SSR/SPA) routes: SSG/ISG output is stored and replayed to every visitor, so a baked-in `Set-Cookie` would fail the prerender build and block ISG revalidation. Path-resolved SSR/SPA responses still vary on `Cookie`, because whether they carry that `Set-Cookie` depends on the incoming cookie; path-only SSG/ISG output stays keyed solely by URL. Cookie config stays browser-valid — `SameSite=None` always forces `Secure`, even if an option tries to disable it. Type the context once via the Register pattern, intersecting with the app's existing registered context type if it has one: ```ts // src/env.d.ts import type { I18nRequestContext } from "@pracht/i18n"; declare module "@pracht/core" { interface Register { context: I18nRequestContext<"en" | "fr">; } } ``` ## Step 4A: Manifest — locale-prefixed URLs One `pathPrefix` group per locale, so only registered locales produce URLs and `/zz/about` 404s instead of serving duplicate default-locale content. Never use a `/:locale` param route for this — it matches any first segment. ```ts import { defineApp, group, route } from "@pracht/core"; const localizedRoutes = [ route("/", "./routes/home.tsx", { render: "ssr" }), route("/about", "./routes/about.tsx", { render: "ssr" }), ]; export const app = defineApp({ middleware: { i18n: "./middleware/i18n.ts" }, routes: [ group({ middleware: ["i18n"] }, [ group({ pathPrefix: "/en" }, localizedRoutes), group({ pathPrefix: "/fr" }, localizedRoutes), route("/", "./routes/locale-redirect.tsx", { render: "ssr" }), ]), ], }); ``` The unprefixed detector redirects using what the middleware resolved. **`return` the redirect** — a *thrown* Response short-circuits past the middleware chain, so the i18n middleware could not stamp `Vary: Cookie, Accept-Language` on it, and a shared cache could replay one visitor's locale redirect to everyone: ```ts // src/routes/locale-redirect.tsx import { redirect, type LoaderArgs } from "@pracht/core"; import { i18n } from "../i18n/index.ts"; export async function loader({ context, request }: LoaderArgs) { return redirect(i18n.localePath("/", context.locale), { request }); } export function Component() { return null; } ``` - Reusing one `localizedRoutes` array is fine with auto-generated ids; with explicit `id`s, each locale's copy needs unique ones. - Route matching is exact and locale prefixes are lowercase — build links with `i18n.localePath()` so they come out canonical. It resolves literal and encoded dot segments before prefixing, so a path assembled from user input cannot escape the locale namespace during browser URL normalization. - SSG/ISG localized routes cannot carry a visitor-specific `Set-Cookie`. In a hydrated component shared by those routes, persist the prefix with `useEffect(() => { i18n.setLocaleCookie(data.locale); }, [data.locale])` so the SSR detector remembers it later (harmless on SSR pages). Without JavaScript, remembering a prerendered visit needs SSR or platform edge middleware ahead of static asset serving. ## Step 4B: Manifest — one URL per page Nothing about the routes changes: add the middleware to the group, skip the prefix groups and the detector route. Detection falls to the cookie, then `Accept-Language`, and the `Vary: Cookie, Accept-Language` header keeps those routes `ssr`/`spa`. Because no URL prefix ever signals an explicit choice, the switcher writes the cookie. Generate an API route so it works with JavaScript disabled: ```ts // src/api/locale.ts import { redirect, type BaseRouteArgs } from "@pracht/core"; import { i18n } from "../i18n/index.ts"; function sameOriginPath(value: FormDataEntryValue | null, base: URL, fallback: string): string { if (typeof value !== "string" || !value.startsWith("/")) return fallback; try { const target = new URL(value, base); return target.origin === base.origin ? `${target.pathname}${target.search}${target.hash}` : fallback; } catch { return fallback; } } export async function POST({ request, url }: BaseRouteArgs) { const form = await request.formData(); const locale = form.get("locale"); if (!i18n.isLocale(locale)) return new Response("Unknown locale", { status: 400 }); // Parse `next` before trusting it: URL normalization can expose an origin. const target = sameOriginPath(form.get("next"), url, "/"); const response = redirect(target, { request, status: 303 }); response.headers.append("set-cookie", i18n.localeCookie(locale, { url })); return response; } ``` Pair it with a `
` switcher: one `