Receive notifications about upcoming Intlayer releases
    Author: AydinTheFirst
    Creation:2025-09-09Last update:2025-09-09

    Getting Started Internationalising (i18n) with Intlayer and Tanstack Start

    This guide demonstrates how to integrate Intlayer for seamless internationalisation in Tanstack Start projects with locale-aware routing, TypeScript support, and modern development practices.

    What is Intlayer?

    Intlayer is an innovative, open-source internationalisation (i18n) library designed to simplify multilingual support in modern web applications.

    With Intlayer, you can:

    • Easily manage translations using declarative dictionaries at the component level.
    • Dynamically localise metadata, routes, and content.
    • Ensure TypeScript support with autogenerated types, improving autocompletion and error detection.
    • Benefit from advanced features, like dynamic locale detection and switching.
    • Enable locale-aware routing with Tanstack Start's file-based routing system.

    Step-by-Step Guide to Set Up Intlayer in a Tanstack Start Application

    Step 1: Create Project

    Start by creating a new TanStack Start project by following the Start new project guide on the TanStack Start website.

    Step 2: Install Intlayer Packages

    Install the necessary packages using your preferred package manager:

    bash
    npm install intlayer react-intlayernpm install vite-intlayer --save-dev
    • intlayer

      The core package that provides internationalisation tools for configuration management, translation, content declaration, transpilation, and CLI commands.

    • react-intlayer The package that integrates Intlayer with React applications. It provides context providers and hooks for React internationalisation.

    • vite-intlayer Includes the Vite plugin for integrating Intlayer with the Vite bundler, as well as middleware for detecting the user's preferred locale, managing cookies, and handling URL redirection.

    Step 3: Configuration of your project

    Create a config file to configure the languages of your application:

    intlayer.config.ts
    import type { IntlayerConfig } from "intlayer";import { Locales } from "intlayer";const config: IntlayerConfig = {  internationalization: {    defaultLocale: Locales.ENGLISH,    locales: [      Locales.ENGLISH,      Locales.FRENCH,      Locales.SPANISH,      // Your other locales    ],  },};export default config;

    Through this configuration file, you can set up localised URLs, middleware redirection, cookie names, the location and extension of your content declarations, disable Intlayer logs in the console, and more. For a complete list of available parameters, refer to the configuration documentation.

    Step 4: Integrate Intlayer in Your Vite Configuration

    Add the intlayer plugin into your configuration:

    vite.config.ts
    import { reactRouter } from "@react-router/dev/vite";import { defineConfig } from "vite";import { intlayerMiddlewarePlugin, intlayerPlugin } from "vite-intlayer";import tsconfigPaths from "vite-tsconfig-paths";export default defineConfig({  plugins: [    reactRouter(),    tsconfigPaths(),    intlayerPlugin(),    intlayerMiddlewarePlugin(),  ],});

    The intlayerPlugin() Vite plugin is used to integrate Intlayer with Vite. It ensures the building of content declaration files and monitors them in development mode. It defines Intlayer environment variables within the Vite application. Additionally, it provides aliases to optimise performance.

    Step 5: Create Layout Components

    Set up your root layout and locale-specific layouts:

    Root Layout

    src/routes/{-$locale}/route.tsx
    // src/routes/{-$locale}/route.tsximport { createFileRoute, Navigate, Outlet } from "@tanstack/react-router";import { configuration } from "intlayer";import { IntlayerProvider, useLocale } from "react-intlayer";import { useI18nHTMLAttributes } from "@/hooks/useI18nHTMLAttributes";export const Route = createFileRoute("/{-$locale}")({  component: LayoutComponent,});function LayoutComponent() {  const { locale } = Route.useParams();  return (    <IntlayerProvider locale={locale}>      <Outlet />    </IntlayerProvider>  );}

    Step 6: Declare Your Content

    Create and manage your content declarations to store translations:

    src/contents/page.content.ts
    import type { Dictionary } from "intlayer";import { t } from "intlayer";const appContent = {  content: {    links: {      about: t({        en: "About",        es: "Acerca de",        fr: "À propos",      }),      home: t({        "en-GB": "Home",        en: "Home",        es: "Inicio",        fr: "Accueil",      }),    },    meta: {      description: t({        "en-GB": "This is an example of using Intlayer with TanStack Router",        en: "This is an example of using Intlayer with TanStack Router",        es: "Este es un ejemplo de uso de Intlayer con TanStack Router",        fr: "Ceci est un exemple d'utilisation d'Intlayer avec TanStack Router",      }),    },    title: t({      "en-GB": "Welcome to Intlayer + TanStack Router",      en: "Welcome to Intlayer + TanStack Router",      es: "Bienvenido a Intlayer + TanStack Router",      fr: "Bienvenue à Intlayer + TanStack Router",    }),  },  key: "app",} satisfies Dictionary;export default appContent;

    Your content declarations can be defined anywhere in your application as soon as they are included in the contentDir directory (by default, ./app). And match the content declaration file extension (by default, .content.{json,ts,tsx,js,jsx,mjs,mjx,cjs,cjx}).

    For more details, refer to the content declaration documentation.

    Step 7: Create Locale-Aware Components and Hooks

    Create a LocalizedLink component for locale-aware navigation:

    src/components/localized-link.tsx
    // src/components/localized-link.tsx// eslint-disable-next-line no-restricted-importsimport { Link, type LinkProps } from "@tanstack/react-router";import { getLocalizedUrl } from "intlayer";import { useLocale } from "react-intlayer";type LocalizedLinkProps = {  to: string;} & Omit<LinkProps, "to">;export function LocalizedLink(props: LocalizedLinkProps) {  const { locale } = useLocale();  const isExternal = (to: string) => {    return /^(https?:)?\/\//.test(to);  };  const to = isExternal(props.to)    ? props.to    : getLocalizedUrl(props.to, locale);  return <Link {...props} to={to as LinkProps["to"]} />;}

    Create a useLocalizedNavigate hook for programme navigation:

    src/hooks/useLocalizedNavigate.tsx
    // src/hooks/useLocalizedNavigate.tsx// eslint-disable-next-line no-restricted-importsimport { NavigateOptions, useNavigate } from "@tanstack/react-router";import { getLocalizedUrl } from "intlayer";import { useLocale } from "react-intlayer";type LocalizedNavigateOptions = {  to: string;} & Omit<NavigateOptions, "to">;export const useLocalizedNavigate = () => {  const navigate = useNavigate();  const { locale } = useLocale();  const isExternal = (to: string) => {    return /^(https?:)?\/\//.test(to);  };  const localizedNavigate = (options: LocalizedNavigateOptions) => {    const to = isExternal(options.to)      ? options.to      : getLocalizedUrl(options.to, locale);    navigate({ ...options, to: to as NavigateOptions["to"] });  };  return localizedNavigate;};

    Step 8: Utilise Intlayer in Your Pages

    Access your content dictionaries throughout your application:

    Root Redirect Page

    src/routes/page.tsx
    // src/routes/page.tsximport { useLocale } from "react-intlayer";import { Navigate } from "react-router";export default function Page() {  const { locale } = useLocale();  return <Navigate replace to={locale} />;}

    Localised Home Page

    src/routes/{-$locale}/index.tsx
    import { createFileRoute } from "@tanstack/react-router";import { getIntlayer } from "intlayer";import { useIntlayer } from "react-intlayer";import LocaleSwitcher from "@/components/locale-switcher";import { LocalizedLink } from "@/components/localized-link";import { useLocalizedNavigate } from "@/hooks/useLocalizedNavigate";export const Route = createFileRoute("/{-$locale}/")({  component: RouteComponent,  head: ({ params }) => {    const { locale } = params;    const metaContent = getIntlayer("app", locale);    return {      meta: [        { title: metaContent.title },        { content: metaContent.meta.description, name: "description" },      ],    };  },});function RouteComponent() {  const content = useIntlayer("app");  const navigate = useLocalizedNavigate();  return (    <div className="grid place-items-center h-screen">      <div className="flex flex-col gap-4 items-center text-centre">        {content.title}        <LocaleSwitcher />        <div className="flex gap-4">          <a href="/">Index</a>          <LocalizedLink to="/">{content.links.home}</LocalizedLink>          <LocalizedLink to="/about">{content.links.about}</LocalizedLink>        </div>        <div className="flex gap-4">          <button onClick={() => navigate({ to: "/" })}>            {content.links.home}          </button>          <button onClick={() => navigate({ to: "/about" })}>            {content.links.about}          </button>        </div>      </div>    </div>  );}

    To learn more about the useIntlayer hook, refer to the documentation.

    Step 9: Create a Locale Switcher Component

    Create a component to allow users to change languages:

    src/components/locale-switcher.tsx
    import { useLocation } from "@tanstack/react-router";import {  getHTMLTextDir,  getLocaleName,  getLocalizedUrl,  Locales,} from "intlayer";import { useIntlayer, useLocale } from "react-intlayer";export default function LocaleSwitcher() {  const { pathname, searchStr } = useLocation();  const content = useIntlayer("locale-switcher");  const { availableLocales, locale, setLocale } = useLocale({    onLocaleChange: (newLocale) => {      const pathWithLocale = getLocalizedUrl(pathname + searchStr, newLocale);      location.replace(pathWithLocale);    },  });  return (    <select      aria-label={content.label.toString()}      onChange={(e) => setLocale(e.target.value)}      value={locale}    >      {availableLocales.map((localeItem) => (        <option          dir={getHTMLTextDir(localeItem)}          key={localeItem}          lang={localeItem}          value={localeItem}        >          {/* Example: Français (French) */}          {getLocaleName(localeItem, locale)} (          {getLocaleName(localeItem, Locales.ENGLISH)})        </option>      ))}    </select>  );}

    To learn more about the useLocale hook, refer to the documentation.

    Step 10: Add HTML Attributes Management (Optional)

    Create a hook to manage HTML lang and dir attributes:

    src/hooks/useI18nHTMLAttributes.tsx
    // src/hooks/useI18nHTMLAttributes.tsximport { getHTMLTextDir } from "intlayer";import { useEffect } from "react";import { useLocale } from "react-intlayer";export const useI18nHTMLAttributes = () => {  const { locale } = useLocale();  useEffect(() => {    document.documentElement.lang = locale;    document.documentElement.dir = getHTMLTextDir(locale);  }, [locale]);};

    Then use it in your root component:

    src/routes/{-$locale}/index.tsx
    import { createFileRoute, Navigate, Outlet } from "@tanstack/react-router";import { configuration } from "intlayer";import { IntlayerProvider, useLocale } from "react-intlayer";import { useI18nHTMLAttributes } from "@/hooks/useI18nHTMLAttributes"; // import the hookexport const Route = createFileRoute("/{-$locale}")({  component: LayoutComponent,});function LayoutComponent() {  useI18nHTMLAttributes(); // add this line  const { locale } = Route.useParams();  return (    <IntlayerProvider locale={locale}>      <Outlet />    </IntlayerProvider>  );}

    Step 11: Build and Run Your Application

    Build the content dictionaries and run your application:

    bash
    # Build Intlayer dictionariesnpm run intlayer:build# Start development servernpm run dev

    Step 12: Configure TypeScript (Optional)

    Intlayer uses module augmentation to gain the benefits of TypeScript and strengthen your codebase.

    Ensure your TypeScript configuration includes the autogenerated types:

    tsconfig.json
    {  compilerOptions: {    // ... your existing TypeScript configurations  },  include: [    // ... your existing includes    ".intlayer/**/*.ts", // Include the auto-generated types  ],}

    Git Configuration

    It is recommended to ignore the files generated by Intlayer. This prevents you from committing them to your Git repository.

    To do this, you can add the following instructions to your .gitignore file:

    .gitignore
    # Ignore the files generated by Intlayer.intlayer

    Step 13: Create Redirection (Optional)

    src/routes/{-$locale}/rotue.tsx
    function LayoutComponent() {  useI18nHTMLAttributes();  const { locale } = Route.useParams();  const { locale: selectedLocale } = useLocale();  const { defaultLocale } = configuration.internationalization;  const { prefixDefault } = configuration.middleware;  // Redirect to the default locale if no locale is present in the URL when prefixDefault is true  if (selectedLocale === defaultLocale && !locale && prefixDefault) {    return <Navigate replace to={defaultLocale} />;  }  // Redirect to the selected locale if the locale in the URL does not match the selected locale  if (selectedLocale !== defaultLocale && !locale) {    return <Navigate replace to={selectedLocale} />;  }  return (    <IntlayerProvider locale={locale}>      <Outlet />    </IntlayerProvider>  );}

    Production Deployment

    When deploying your application:

    1. Build your application:

      bash
      npm run build
    2. Build Intlayer dictionaries:

      bash
      npm run intlayer:build
    3. Move vite-intlayer to dependencies if using middleware in production:

      bash
      npm install vite-intlayer --save

    Your application will now support:

    • URL Structure: /en, /en/about, /tr, /tr/about
    • Automatic locale detection based on browser preferences
    • Locale-aware routing with Tanstack Start
    • TypeScript support with auto-generated types
    • Server-side rendering with proper locale handling

    VS Code Extension

    To improve your development experience with Intlayer, you can install the official Intlayer VS Code Extension.

    Install from the VS Code Marketplace

    This extension provides:

    • Autocompletion for translation keys.
    • Real-time error detection for missing translations.
    • Inline previews of translated content.
    • Quick actions to easily create and update translations.

    For more details on how to use the extension, refer to the Intlayer VS Code Extension documentation.


    Go Further

    To go further, you can implement the visual editor or externalise your content using the CMS.


    Documentation References

    This comprehensive guide provides everything you need to integrate Intlayer with Tanstack Start for a fully internationalised application with locale-aware routing and TypeScript support.

    Doc History

    Version Date Changes
    5.8.1 2025-09-09 Added for Tanstack Start
    Receive notifications about upcoming Intlayer releases