Translate a TanStack Start application

Resolve locale-prefixed requests, load the matching catalog, and render translated pages with canonical URLs and a language switcher.

Keep application routes such as /about independent of language, while readers visit /en/about or /de/about. @lingo.dev/react-tanstack connects that URL policy to request context and catalogs. The route still matches /about; the request's locale determines its messages and the URLs generated from it.

This recipe adds English and German to an existing TanStack Start application with React 19, TanStack Router 1.170+, and Start 1.168+. Start is declared as an optional peer, but the package's root module imports Start's createIsomorphicFn. Install it alongside the adapter even if a plain Router application supplies an explicit URL.

Define the locale policy and catalog #

Install the packages:

sh
npm install @lingo.dev/react@1.17.1 @lingo.dev/react-tanstack@1.17.1 @lingo.dev/locale-router@0.2.1
npm install @lingo.dev/spec@1.17.1 jsonc-parser
npm install --save-dev @lingo.dev/cli@latest

Add the loadMatchedMessages function from catalog loading as src/catalog.ts. Then create src/i18n.ts:

ts
import { createLocaleRouter } from "@lingo.dev/locale-router";
import type { Catalog } from "@lingo.dev/react-tanstack";
import source from "../locales/en.jsonc?raw";
import { loadMatchedMessages } from "./catalog";

export const locales = createLocaleRouter(["en", "de"] as const, {
  defaultLocale: "en",
  exclude: ["api", "assets"],
});

const targets = import.meta.glob<string>("../locales/*.jsonc", {
  query: "?raw",
  import: "default",
});

export const catalog: Catalog = async (locale) => {
  const load = targets[`../locales/${locale}.jsonc`];
  if (!load) throw new Error(`Missing catalog for ${locale}`);
  return loadMatchedMessages(source, await load());
};

This Vite loader validates the raw files and selects active keys from the matching English source, so comment-free translated output does not reactivate orphans. It fails for missing or malformed files rather than silently serving an empty map. The extraction step below creates the imported source before the application starts.

Resolve the request before creating the router #

Register the bare-path middleware in src/start.ts, retaining any existing middleware:

ts
import { createStart } from "@tanstack/react-start";
import { localeMiddleware } from "@lingo.dev/react-tanstack/server";
import { locales } from "./i18n";

export const startInstance = createStart(() => ({
  requestMiddleware: [localeMiddleware(locales)],
}));

In src/router.tsx, use the resolved locale and messages as router context:

tsx
import { createRouter } from "@tanstack/react-router";
import { lingoContext, localeRewrite } from "@lingo.dev/react-tanstack";
import { routeTree } from "./routeTree.gen";
import { catalog, locales } from "./i18n";

export async function getRouter() {
  const state = await lingoContext(locales, catalog);
  return createRouter({
    routeTree,
    context: state,
    rewrite: localeRewrite(locales, state.locale),
  });
}

declare module "@tanstack/react-router" {
  interface Register {
    router: Awaited<ReturnType<typeof getRouter>>;
  }
}

Keep the application's other router settings. lingoContext takes the recognized URL prefix or uses the default locale. It reads the request URL on the server and location.href in the browser; an optional third URL argument makes that input explicit. It does not negotiate Accept-Language itself. The middleware performs that negotiation for eligible bare-path requests and responds with a 302 redirect.

localeRewrite removes a recognized prefix for route matching and adds the request locale to outgoing eligible paths. Keep route definitions unprefixed, and exclude API/assets paths from localization as above.

Render the root from request context #

In src/routes/__root.tsx, preserve the framework shell while supplying the provider:

tsx
import { createRootRouteWithContext, HeadContent, Outlet, Scripts } from "@tanstack/react-router";
import { createLingo, LingoProvider, type Messages } from "@lingo.dev/react";

type LocaleContext = { locale: "en" | "de"; messages: Messages };

export const Route = createRootRouteWithContext<LocaleContext>()({
  component: Outlet,
  shellComponent: ({ children }) => {
    const { locale, messages } = Route.useRouteContext();
    return (
      <html lang={locale} dir={createLingo(locale).direction}>
        <head>
          <HeadContent />
        </head>
        <body>
          <LingoProvider locale={locale} messages={messages}>
            {children}
          </LingoProvider>
          <Scripts />
        </body>
      </html>
    );
  },
});

The same context now drives text, formatting, and document attributes. Preserve it during hydration; replacing the messages with an empty client map would change the rendered page.

Add a translated page and head metadata #

Create src/routes/about.tsx:

tsx
import { createFileRoute } from "@tanstack/react-router";
import { useLingo } from "@lingo.dev/react";
import { getLingo, lingoHead } from "@lingo.dev/react-tanstack";
import { locales } from "../i18n";

export const Route = createFileRoute("/about")({
  head: (options) => {
    const l = getLingo(options);
    const localized = lingoHead({
      router: locales,
      locale: options.match.context.locale,
      pathname: options.match.pathname,
      origin: "https://example.com",
    });
    return {
      meta: [{ title: l.text("About us", { context: "About page title" }) }, ...localized.meta],
      links: localized.links,
    };
  },
  component: About,
});

function About() {
  const l = useLingo();
  return <h1>{l.text("About us", { context: "About page heading" })}</h1>;
}

Replace the example origin with your trusted site origin. Bind const l = getLingo(options) before extracted calls in head; a chained getLingo(options).text(...) is not the supported extraction pattern.

Head metadata #

lingoHead returns { meta, links }: canonical and alternate links for each locale plus x-default, and og:url/og:locale. Supply an unprefixed pathname without query or hash. For German /about, the canonical URL is https://example.com/de/about; the default English alternate is /en/about under this policy.

The helper removes one trailing slash from non-root paths. Open Graph locale derives from maximized language/region, such as de_DE; optional ogLocale overrides handle platform-specific spellings. LingoHead is the result type, not the Next adapter's JSX component.

Extract and retrieve the catalogs #

Run npx lingo extract --src src --source-locale en. For a new configuration, initialize locales/en.jsonc with targets de, authenticate, link a localization engine, and retrieve the first target:

sh
npx lingo init --source en --targets de --files 'locales/en.jsonc' --yes
npx lingo login
npx lingo link
npx lingo push --backfill-missing --wait

For an existing configuration, preserve its bindings and advanced settings. After extraction, complete ordinary updates for existing targets, retrieve and inspect them, then add de and backfill while keeping the source revision fixed. Follow Catalog loading and the language-addition procedure for that branch. Start the application only after locales/en.jsonc and the intended locales/de.jsonc are present. Visit /en/about and /de/about, inspect the heading and title, and check their canonical/alternate URLs.

Switch language with a full request #

tsx
import { useLocaleSwitch } from "@lingo.dev/react-tanstack";
import { locales } from "./i18n";

export function Languages() {
  const options = useLocaleSwitch(locales);
  return (
    <nav aria-label="Language">
      {options.map((option) => (
        <a key={option.locale} href={option.href} aria-current={option.current ? "page" : undefined}>
          {option.label}
        </a>
      ))}
    </nav>
  );
}

Place this component under src and render it within the routed application. Each option contains locale, an endonym label, href, and current. Plain anchors make a new request and load that locale's catalog. Client-only route links can retain the old request's messages. The switcher preserves query and hash and excludes x-default from selectable languages.

Built-in catalog and server helpers #

createCatalog(import.meta.glob("../locales/*.jsonc", { query: "?raw" }), { sourceLocale: "en" }) provides a cached Catalog for files whose metadata can be used directly. Its modules must resolve to objects with string default exports. It filters orphans present in those files, caches one promise per locale, and returns {} for missing modules, loading errors, or parse errors. With sourceLocale set, it skips that locale's file in production and uses source fallback. It does not validate flat string-valued shapes, filter by route, or restore lost metadata; the source-join loader above handles those needs for translated JSONC.

The server entry exports localeMiddleware and canonicalSearch. The middleware preserves search parameters but reserializes them through TanStack's defaults; server requests have no browser hash. Paths already prefixed, excluded, or eligible for separate canonical normalization proceed to next(). Use locale-router for exact prefix and canonicalization behavior.

A plain TanStack Router application can supply a URL to lingoContext and implement its own redirects, while retaining the root package's Start dependency. This recipe's middleware and request shell specifically target Start.