@lingo.dev/react-tanstack
v1.22.0
Published
Lingo.dev for TanStack Start and TanStack Router: locale rewrite, bare-path redirect, message catalog, request context, head tags and a language switcher over @lingo.dev/locale-router.
Keywords
Readme
@lingo.dev/react-tanstack
Lingo.dev for TanStack Start and TanStack Router: the eight pieces a localized TanStack app needs, composed over a @lingo.dev/locale-router. A rewrite that strips and re-adds the locale prefix, a request middleware that sends a bare path to its negotiated locale, a Vite plugin that compiles the locale files at build time, a message catalog loaded once per locale, the { locale, messages } context a request renders in, a Lingo for head() (which cannot use hooks), canonical and hreflang tags, and a language switcher. The TanStack twin of @lingo.dev/react-next.
Getting started
// vite.config.ts
export default defineConfig({ plugins: [lingoCatalog(), tanstackStart(), viteReact()] });
// src/i18n.ts
export const locales = createLocaleRouter(["en", "de", "ja"] as const, { defaultLocale: "en" });
export const catalog = createCatalog(import.meta.glob("../locales/*.jsonc", { query: "?lingo" }), {
sourceLocale: "en",
});
// src/start.ts
export const startInstance = createStart(() => ({ requestMiddleware: [localeMiddleware(locales)] }));
// src/router.tsx
export async function getRouter() {
const { locale, messages } = await lingoContext(locales, catalog);
return createRouter({ routeTree, context: { locale, messages }, rewrite: localeRewrite(locales, locale) });
}
// __root.tsx: head() calls getLingo(options) for copy, lingoHead({ router: locales, locale, pathname, origin }) for canonical and hreflang;
// shellComponent renders <html lang={locale}> around <LingoProvider locale messages>.createLocaleRouter comes from @lingo.dev/locale-router; lingoCatalog from @lingo.dev/react-tanstack/vite; createCatalog, lingoContext, localeRewrite, getLingo, lingoHead and useLocaleSwitch from this package's root entry, where createCatalog is re-exported from @lingo.dev/spec and lingoHead from @lingo.dev/locale-router; localeMiddleware from @lingo.dev/react-tanstack/server; LingoProvider and useLingo from @lingo.dev/react.
The root route's head and its shell in full:
export const Route = createRootRouteWithContext<{ locale: string; messages: Messages }>()({
head: (options) => {
const l = getLingo(options);
const url = new URL(options.matches.at(-1)?.pathname ?? "/", "https://example.com");
return {
meta: [
{ title: l.text("Welcome", { context: "Home page title" }) },
...lingoHead({
router: locales,
locale: options.match.context.locale,
pathname: url.pathname,
origin: url.origin,
}).meta,
],
links: lingoHead({
router: locales,
locale: options.match.context.locale,
pathname: url.pathname,
origin: url.origin,
}).links,
};
},
shellComponent: ({ children }) => {
const { locale, messages } = Route.useRouteContext();
return (
<html lang={locale}>
<head>
<HeadContent />
</head>
<body>
<LingoProvider locale={locale} messages={messages}>
{children}
</LingoProvider>
<Scripts />
</body>
</html>
);
},
});lingo extract tracks strings through a receiver named l, so bind const l = getLingo(options) before calling l.text; a one-line getLingo(options).text(...) would orphan the string.
API
@lingo.dev/react-tanstack
| Export | Does |
| ------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| localeRewrite(router, locale) | A LocationRewrite for createRouter. input strips any listed locale prefix so routes never carry a $locale segment; output prefixes the request's locale onto every href the router builds. Paths the router does not localize (excluded segments, _ internals, files) pass through untouched. |
| lingoContext(router, catalog, url?) | Promise<{ locale, messages }> for the router's context. Reads the locale off the URL prefix (the request URL on the server, location.href in the browser, or the url you pass) and loads that locale's catalog. |
| createCatalog(modules, { sourceLocale? }) | A Catalog over import.meta.glob("…/*.jsonc", { query: "?lingo" }), the files lingoCatalog() compiled: memoises one promise per locale, answers {} for a locale without a file or one that fails to load, and ships no file for sourceLocale when NODE_ENV is production, since every lookup falls back to the source string. Deprecated: { query: "?raw" } still works, parsed in the browser by a lazily loaded parser with a one-time development warning. |
| getLingo(options) | A Lingo for a route's head(), which cannot call useLingo(). Reads options.match.context.locale and .messages. |
| lingoHead({ router, locale, pathname, origin, ogLocale? }) | { meta, links }: a canonical link, one alternate per locale plus x-default, og:url and og:locale. The platform locale (de_DE) derives from Intl.Locale.maximize(); pass ogLocale: { "es-419": "es_LA" } where a platform spells it otherwise. A trailing slash the router kept is dropped. |
| useLocaleSwitch(router) | ReadonlyArray<{ locale, label, href, current }> for a language switcher: the page the reader is on under every locale, query and hash kept, each language named in itself (Intl.DisplayNames), the locale being read marked. Render each as a plain <a href>, never a <Link>: the catalog is fixed per request, so a client-side move would keep the old language. |
@lingo.dev/react-tanstack/server
| Export | Does |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| localeMiddleware(router) | A Start request middleware. A localized path without a prefix answers 302 to router.redirect(url, acceptLanguage), its search spelled the way the router reads it; everything else goes to next(). |
| canonicalSearch(search) | A search string re-serialised the way the router will read it (?next=/en/me → ?next=%2Fen%2Fme). A redirect that lands on any other spelling reloads once more when the router canonicalises the address. |
@lingo.dev/react-tanstack/vite
Re-exports lingoCatalog from @lingo.dev/vite.
| Export | Does |
| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| lingoCatalog() | A Vite plugin that compiles each *.jsonc?lingo import, in builds and in the dev server, into a module whose default export is { key: value } for the file's active entries: comments and @orphan entries are dropped and values, ICU included, pass through unchanged. A malformed file or a value that is not a string fails the build with the file, line and column. Editing a file reloads it in dev. Other imports, ?raw included, are untouched. |
Peers
@lingo.dev/react, @tanstack/react-router >= 1.170 (the release that added LocationRewrite), react. @tanstack/react-start >= 1.168 is declared optional, but the root entry reads the request URL through its createIsomorphicFn and ./server builds on its createMiddleware, so install it alongside; a plain TanStack Router app passes url to lingoContext and does its own redirect. vite >= 6 is an optional peer for ./vite.
