DocsTanStack Start
@generic-translation/tanstack-start reference
resolveLocale, loadGenericTranslation, GenericTranslationProvider, cookie helpers and locale-prefixed routing for TanStack Start.
On this page
Generic Translation for TanStack Start. The server decides the visitor’s locale, loads that locale’s translations, and the page renders translated on the first byte. Source: generic-translation/generic-translation-tanstack-start. See the quickstart for setup.
Not on npm yet, and not tested in a real browser session. Clone generic-translation/generic-translation with --recurse-submodules and link the packages. See what was verified.
Peer dependencies: react >= 18, @tanstack/react-router, and optionally @tanstack/react-start (only your own server functions import it). Written against TanStack Start 1.17x.
The package re-exports the whole @generic-translation/react surface under the same names (T, Var, Num, Currency, DateTime, RelativeTime, Plural, Branch, LocaleSelector, useGenericTranslation, useDictionary, useLocale, useSetLocale, useLocales, useLocaleProperties, useLocaleDirection, useGenericTranslationContext, serializeChildren, localizePath) except GenericTranslationProvider, which is replaced by a server-driven one. <T> is the unmodified @generic-translation/react component, and the CLI treats imports from @generic-translation/tanstack-start exactly like imports from @generic-translation/react. See React components.
| Entry point | Use it in |
|---|---|
@generic-translation/tanstack-start |
Components, routes, router setup (isomorphic, no Node APIs) |
@generic-translation/tanstack-start/server |
Server functions and server-only modules (reads public/_generic-translation/*.json) |
resolveLocale and resolveLocaleDetailed
resolveLocale(request, { locales: ["es", "fr"], defaultLocale: "en", localePrefix: "never", cookieName: "generic-translation-locale" }): string
The order is: URL prefix (only when localePrefix is "as-needed" or "always"), the generic-translation-locale cookie, Accept-Language, then defaultLocale. It uses determineLocale from @generic-translation/core, so fr-CA negotiates to fr, and the result is always one of the configured locales. Under "as-needed" an unprefixed URL means the default locale unless the cookie says otherwise, with no Accept-Language guessing, so URLs stay canonical. resolveLocaleDetailed also returns source ("url", "cookie", "accept-language" or "default") and the prefix-stripped pathname. request may be a Request or anything with url and headers.get.
loadGenericTranslation (server entry)
const data = await loadGenericTranslation({ ...config, request }); // or { context: { request } } or { locale: "fr" }
// { locale, defaultLocale, locales, direction, translations }
translations come from, in order: loadTranslations(locale) if you pass one, then {translationsDir}/{locale}.json (default public/_generic-translation, relative to process.cwd()), then the Generic Translation CDN when projectId is set (baseUrl and fetch are optional). Maps are cached in memory for cacheTtlMs (default 60 s; 0 disables). It never throws: a missing or broken source logs a warning and yields {}, so the page renders the source text. The default locale, and same-language locales, skip loading. On serverless or edge hosts without a file system use loadTranslations or projectId. createGenericTranslation(config) binds the config once; loadTranslationMap, loadTranslationsFromDisk and clearTranslationCache are also exported.
Call it from a server function used by the root route’s loader (or beforeLoad). The result is plain JSON and safe to serialize into the page.
GenericTranslationProvider
<GenericTranslationProvider loaderData onSetLocale? localePrefix? dictionary? …> wraps the @generic-translation/react provider with locale and translations taken from loaderData. There is no client-side detection, so SSR and the first client render are identical and <html lang dir> stays in sync. Other @generic-translation/react provider props (dictionary, onLocaleChange, devApiKey, …) pass through.
setLocale(locale), from useSetLocale() or <LocaleSelector>:
- ignores unsupported locales (after negotiation) and the current one;
- calls
onSetLocale(locale), typically yoursetLocaleFnthat sets the cookie on the response (without it,document.cookieis written in the browser); - with a
localePrefixother than"never", pushes the localized URL; - awaits
router.invalidate()so the root loader runs again with the new cookie and the new translations flow into the provider. The old locale stays until the new data arrives.
Cookie helpers
LOCALE_COOKIE ("generic-translation-locale"), parseCookieHeader(header) and serializeLocaleCookie(locale, { maxAge, path, domain, sameSite, secure, name }), which returns a Set-Cookie value for custom middleware or Response headers.
Locale-prefixed routing
Optional. Routes are written once, without a prefix. A router rewrite strips /fr on the way in and adds it back to generated links:
// src/router.tsx
import { createRouter } from "@tanstack/react-router";
import { createLocaleRewrite } from "@generic-translation/tanstack-start";
import { routeTree } from "./routeTree.gen";
export function getRouter() {
// Create one per router: it remembers the locale of the URL being rendered (per request on the server).
const rewrite = createLocaleRewrite({ locales: ["es", "fr"], defaultLocale: "en", localePrefix: "as-needed" });
return createRouter({ routeTree, rewrite });
}
Give the same localePrefix to resolveLocale / loadGenericTranslation (so the URL decides) and to <GenericTranslationProvider localePrefix> (so switching moves to the localized URL). For links use LocalizedLink, a Link that rebuilds its href when the locale changes; a plain Link keeps a stale prefix. localizeHref(href, locale, config) converts a path for non-router uses, and stripLocalePrefix(pathname, config) does the reverse. To redirect an unprefixed URL to the visitor’s language, compare resolveLocaleDetailed(request, …) with the URL in beforeLoad and throw redirect({ href: localizeHref(...) }).
Other exports
getHtmlAttributes(locale) returns { lang, dir }; allLocales(config); and the types LocaleConfig, LocalePrefix, GenericTranslationLoaderData, GenericTranslationServerConfig, GenericTranslationData, RequestLike, ResolvedLocale, LocaleRewrite.
What was verified
- Unit tests (vitest): locale resolution (cookie,
Accept-Language, prefixes, plain request objects), cookie parse and serialize, prefix helpers and the rewrite pair,loadGenericTranslationagainst a temp translations directory, a custom loader, a fake-fetch CDN, the TTL cache and broken files, SSR withreact-dom/serverfollowed byhydrateRoot(no mismatch warnings, no locale flip), andsetLocalewith a real TanStack router on a memory history. - The example app was built with
vite build(Start 1.170, Vite 8) and its production server handler was invoked directly withRequests: the HTML came back translated forAccept-Language: fr, cookiees,ar(withdir="rtl") and the default. - Not verified: a browser session against a running dev server (client-side navigation through the
getGenericTranslationDataRPC, thesetLocaleFnPOST and the cookie round trip), deployment adapters and edge runtimes, and Start versions other than 1.170.
Design notes
The package ships plain helpers rather than ready-made server functions: Start’s compiler only splits createServerFn calls in application source, and a factory shipped from node_modules was left in the client bundle. That is why the two short functions live in your app, and why GenericTranslationProvider takes the setter as onSetLocale.
Something wrong or unclear on this page? Open an issue.