add-i18n
Skill106 starsChanged 7 months agoMITView on GitHub
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".
- Installs packages
- Sends data out
3 other projects use a version of this.
Adopted by
Most recently taken up by
- flavien-ia/hypervibe-crafttheir own version, first seen Oct 25, 2026
- flavien-ia/hypervibe-harnesstheir own version, first seen Oct 23, 2026
- buildpad-ai/skillstheir own version, first seen Oct 16, 2026
Other versions3 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 3
- flavien-ia/hypervibe-craft★ 50same name
- flavien-ia/hypervibe-harness★ 50same name
- buildpad-ai/skills★ 1same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository33 other files it gives its agents.
- AGENTS.mdAGENTS.md
- add-authSkill
- add-capabilitiesSkill
- add-contentSkill
- add-dbSkill
- add-imagesSkill
- add-observabilitySkill
- add-openapiSkill
- audit-a11ySkill
- audit-agent-surfaceSkill
- audit-authSkill
- audit-bundlesSkill
- audit-csrfSkill
- audit-depsSkill
- audit-headersSkill
- audit-islandsSkill
- audit-loadersSkill
- audit-redirectsSkill
- audit-secretsSkill
- audit-seoSkill
- audit-shellsSkill
- configure-isgSkill
- migrate-nextjsSkill
- pracht-debugSkill
- pracht-deploySkill
- pracht-scaffoldSkill
- pracht-test-apiSkill
- pre-deploySkill
- scaffold-e2eSkill
- scaffold-testsSkill
- tune-render-modeSkill
- typed-routesSkill
- upgrade-prachtSkill
The file
We split this skill into the rules it gives an agent
8 rules. 0 are common, 2 are distinctive, and 6 are very specific to this project.
0
Common
Most of the 3 edited versions we read keep these.
2
Distinctive
This author's own choices. Worth a look.
6
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 36
Use AskUserQuestion once for the supported locales (default en plus one or two), the default locale, and the URL strategy:
- Distinctive: line 47
Never migrate a live app's URLs without saying so explicitly.
- Very specific: line 293
Keep the detector route SSR.
- Very specific: line 303
Update the sitemap to include every per-locale URL (see /audit-seo).
- Very specific: line 310
Run pracht typegen if step 4 changed route paths or added the API route, and add pracht typegen --check to CI.
- Very specific: line 336
Only registered locales may reach paths, cookies, or hreflang.
- Very specific: line 350
Never bundle every translation into the client.
- Distinctive: line 352
Never move an existing app's URLs without asking.
“Common” is measured: kept by at least 6 in 10 of the 3 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
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:
https://pracht.resynapse.dev/docs/recipes/i18n — which also carries a
hand-rolled fallback recipe if the user refuses the dependency. Working setups
of both strategies live in
https://github.com/JoviDeCroock/pracht/tree/main/examples/basic:
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.
npm install @pracht/i18nStep 2: Instance and dictionaries
// 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:
// 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
// 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:
// 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.
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:
// 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
localizedRoutesarray is fine with auto-generated ids; with explicitids, 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 withuseEffect(() => { 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:
// 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 <Form method="post" action="/api/locale"> switcher: one
<button name="locale" value={locale}> per locale plus a hidden next field
carrying useLocation().pathname + useLocation().search, so switching does not
drop the current query. Hydrated, <Form> uses the framework's redirect
handshake and re-runs the loader; without JavaScript the browser follows the
303.
For an instant switch with no request, i18n.setLocaleCookie(locale) writes the
same cookie from the browser and await dictionaries.load(locale) swaps the
dictionary in place. That path is easy to get wrong — hold the dictionary in
state, reset it when loader data changes, and set document.documentElement.lang
and a localized document.title by hand (head() already ran server-side).
Then:
- Load the dictionary before writing the cookie.
- Guard concurrent lazy loads with a monotonically increasing request id so only the latest successful selection commits both cookie and state.
- Catch import failures rather than leaving an unhandled event-handler rejection or a half-applied locale.
- Invalidate that request id from a
useLayoutEffectcleanup keyed by loader messages, so a loader-data change or unmount wins during commit; a passiveuseEffectcleanup leaves time for a stale import to write its cookie. - Increment the shared request id synchronously in the server switcher's
<Form onSubmit>and before any other navigation that can replace loader data — cleanup at commit cannot undo a stale cookie written mid-transition.
i18n.detectClient() is the browser-side detect() when a client-only surface
must resolve the locale itself.
Step 5: Loaders and components
import type { HeadArgs, LoaderArgs, RouteComponentProps } from "@pracht/core";
import { t } from "@pracht/i18n";
import { dictionaries, i18n } from "../i18n/index.ts";
import { useEffect } from "preact/hooks";
export async function loader({ context }: LoaderArgs) {
const messages = await dictionaries.load(context.locale);
return { locale: context.locale, messages };
}
export function head({ data, url }: HeadArgs<typeof loader>) {
return {
lang: data.locale,
title: t(data.messages, "home.title"),
link: i18n.hreflang(url.pathname, { origin: "https://example.com" }),
};
}
export function Component({ data }: RouteComponentProps<typeof loader>) {
// Required for SSG/ISG locale routes; harmless when SSR middleware already
// persisted the matching path locale.
useEffect(() => {
i18n.setLocaleCookie(data.locale);
}, [data.locale]);
return <h1>{t(data.messages, "home.title", { name: "Jovi" })}</h1>;
}messages is a plain serializable object, so the same t() calls work after
hydration and on client navigations. hreflang() emits one alternate per
locale plus x-default pointing at the unprefixed detector — pass the app's
canonical origin. Relative previews stay current-origin because splitLocale()
keeps the stripped pathname root-relative, and every alternate preserves an
input query/hash suffix. Under strategy B, omit the link entry entirely:
there is no alternate URL, so emitting hreflang would be a lie.
Step 6: SEO
- Set
langfrom the resolved locale inhead(). - Keep the detector route SSR. Locale-prefixed routes may be
ssg/isg— every prefixed URL is a real route, and the middleware skips cookie persistence there so noSet-Cookielands in stored output. Keep"path"first in the detect order for prerendered routes: cookie/header detection cannot run against a stored document (prerender/ISG requests carry no cookies orAccept-Language), and a route that depends on those sources getsVary: Cookieand is refused by the ISG cache. - Prerendered
head()runs against a placeholder request origin — pass the canonical origin tohreflang()on SSG/ISG routes instead ofurl.origin, or the alternates bake inhttp://localhost. - Update the sitemap to include every per-locale URL (see
/audit-seo). - Strategy B only: one URL means one indexed language, whatever the crawler's
Accept-Languageresolves to. Say that out loud — if it matters, that is the argument for strategy A. Still setlang; sitemap entries stay as-is.
Step 7: Verify
Run pracht typegen if step 4 changed route paths or added the API route, and
add pracht typegen --check to CI. Boot pracht dev, then:
- Strategy A.
curl -ithe unprefixed detector withAccept-Language: fr(302 to/fr/...), with apracht_localecookie (cookie beats header), and with garbage (;q=, unknown tags → default locale). On a locale-prefixed page, confirm translated content and hreflang links. On SSR, confirmSet-Cookieon first visit andVary: Cookiewhether or not the request cookie already matches. On SSG/ISG, confirm the stored response has neitherSet-Cookienor a path-onlyVary, that hydration writes the locale cookie, and that the unprefixed detector then returns to that locale./zz/aboutmust 404. - Strategy B.
curl -ithe page withAccept-Language: fr(French content,Vary: Cookie, Accept-Language, noSet-Cookie), and withCookie: pracht_locale=frplusAccept-Language: en(cookie wins).curl -i -X POSTthe switcher with-d locale=frand anOriginheader matching the host (mutation API routes are same-origin-checked): expect 303 +Set-Cookie. Post an unregistered locale and an off-originnext: expect 400 and a same-origin redirect. In the browser, switch and confirm the URL never changes. pnpm test,pnpm e2e, andpracht verify --jsonall pass.
Rules
- The middleware sets
context.locale; loaders read it. Never stash the locale in module-level state — concurrent requests collide. - Only registered locales may reach paths, cookies, or hreflang.
defineI18n/localePathenforce that; never bypass them with string concatenation on user input. Accept-Languagehandling is already conservative and must stay that way: wildcard fallbacks resolve through the registered locale list, explicitq=0exclusions hold against both lookup truncation and best-fit fallback, directly matched longer variants win before same-language best fit (which never crosses conflicting script subtags), and an entry cut in half by the defensive header-length limit is discarded rather than parsed with an implied quality of 1.- For SSG with dynamic segments,
getStaticPathsmust return the locale × dynamic-param product — prerender only URL combinations that exist. - Format dates and numbers with
Intl.DateTimeFormat/Intl.NumberFormatanddata.locale; no library needed. - Never bundle every translation into the client.
createDictionariesloaders are per-locale lazy imports resolved in loaders — keep them that way. - Never move an existing app's URLs without asking. If the user says their URLs are fixed, strategy B is the answer, not a redirect table.
$ARGUMENTS
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

