Creation:2026-04-24Last update:2026-05-31

    Translate your Astro + Vanilla JS site with Intlayer | Internationalisation (i18n)

    ide.intlayer.org

    Table of Contents

    Why Intlayer over alternatives?

    Compared to main solutions like astro-i18n or i18next, Intlayer is a solution that comes with integrated optimizations such as:

    Intlayer is optimized to work perfectly with Astro by offering multilingual routing, sitemap, and all the features needed for scaling internationalization (i18n).

    Instead of loading massive JSON files into your pages, load only the necessary content. Intlayer helps reduce your bundle and page sizes by up to 50%.

    Scoping your application's content facilitates maintenance for large-scale applications. You can duplicate or delete a single feature folder without the mental burden of reviewing your entire content codebase. Additionally, Intlayer is fully typed to ensure your content's accuracy.

    Co-locating content reduces the context needed by Large Language Models (LLMs). Intlayer also comes with a suite of tools, such as a CLI to test for missing translations,LSP, MCP, and agent skills, to make the developer experience (DX) even smoother for AI agents.

    Use automation to translate in your CI/CD pipeline using the LLM of your choice at the cost of your AI provider. Intlayer also offers a compiler to automate content extraction, as well as a web platform to help translate in the background.

    Connecting massive JSON files to components can lead to performance and reactivity issues. Intlayer optimizes your content loading at build time.

    More than just an i18n solution, Intlayer provides an self-hosted visual editor and a full CMS to help you manage your multilingual content in real-time, making collaboration with translators, copywriters, and other team members seamless. Content can be stored locally and/or remotely.


    Step-by-Step Guide to Configure Intlayer in Astro + Vanilla JS

    Check out the application template on GitHub.

    1. Install Dependencies

      Install the necessary packages using your preferred package manager:

      bash
      npm install intlayer astro-intlayer vanilla-intlayernpx intlayer init
      • intlayer The core package that provides i18n tools for configuration management, translations, content declaration, transpilation, and CLI commands.

      • astro-intlayer Includes the Astro integration plugin to link Intlayer with the Vite bundler, as well as the middleware to detect the user's preferred language, manage cookies, and handle URL redirects.

      • vanilla-intlayer A package to integrate Intlayer into Vanilla JavaScript / TypeScript applications. It provides a Pub/Sub singleton (IntlayerClient) and callback-based helpers (useIntlayer, useLocale, etc.), allowing any part of your Astro <script> tags to respond to language changes without the need for a UI framework.

    2. Configure Your Project

      Create a configuration file to define your application's languages:

      intlayer.config.ts
      import { Locales, type IntlayerConfig } from "intlayer";const config: IntlayerConfig = {  internationalization: {    locales: [      Locales.ENGLISH,      Locales.FRENCH,      Locales.SPANISH,      Locales.ENGLISH_UNITED_KINGDOM,      // Your other languages    ],    defaultLocale: Locales.ENGLISH,  },};export default config;
      Through this configuration file, you can configure localised URLs, middleware redirects, cookie names, location and extensions of content declarations, disable Intlayer logs in the console, and more. For a full list of available parameters, refer to the configuration documentation.
    3. Integrate Intlayer into Your Astro Configuration

      Add the intlayer plugin to your Astro configuration. For Vanilla JS, no additional UI framework integration is required.

      astro.config.ts
      // @ts-checkimport { intlayer } from "astro-intlayer";import { defineConfig } from "astro/config";// https://astro.build/configexport default defineConfig({  integrations: [intlayer()],});
      The intlayer() integration plugin is used to integrate Intlayer with Astro. It ensures the generation of the content declaration files and monitors them in development mode. It defines Intlayer environment variables within the Astro application and provides aliases to optimise performance.
    4. Declare Your Content

      Create and manage your content declarations to store translations:

      src/app.content.ts
      import { t, type Dictionary } from "intlayer";const appContent = {  key: "app",  content: {    greeting: t({      en: "Hello World",      fr: "Bonjour le monde",      es: "Hola mundo",      "en-GB": "Hello World",    }),    description: t({      en: "Welcome to my multilingual Astro site.",      fr: "Bienvenue sur mon site Astro multilingue.",      es: "Bienvenido a mi sitio Astro multilingüe.",      "en-GB": "Welcome to my multilingual Astro site.",    }),    switchLocale: t({      en: "Switch language:",      fr: "Changer de langue :",      es: "Cambiar idioma:",      "en-GB": "Change language:",    }),  },} satisfies Dictionary;export default appContent;
      Content declarations can be defined anywhere in your application, as long as they are included in the contentDir (by default ./src) and match the content declaration file extension (by default .content.{json,ts,tsx,js,jsx,mjs,cjs}).
      For more information, refer to the content declaration documentation.
    5. Using Content in Astro

      With Vanilla JS, all server-side rendering happens directly in .astro files using getIntlayer. Subsequently, a <script> block initialises vanilla-intlayer on the client to enable language switching.

      src/pages/[...locale]/index.astro
      ---import {  getIntlayer,  getLocaleFromPath,  getLocalizedUrl,  getPrefix,  getLocaleName,  localeMap,  locales,  defaultLocale,  getPathWithoutLocale,  type LocalesValues,} from "intlayer";export const getStaticPaths = () => {  return localeMap(({ locale }) => ({    params: { locale: getPrefix(locale).localePrefix },  }));};const locale = getLocaleFromPath(Astro.url.pathname) as LocalesValues;const pathWithoutLocale = getPathWithoutLocale(Astro.url.pathname);const { greeting, description, switchLocale } = getIntlayer("app", locale);---<!doctype html><html lang={locale} dir={getHTMLTextDir(locale)}>  <head>    <meta charset="utf-8" />    <meta name="viewport" content="width=device-width" />    <link rel="icon" type="image/svg+xml" href="/favicon.svg" />    <title>{greeting}</title>    <!-- Canonical Link -->    <link      rel="canonical"      href={new URL(getLocalizedUrl(Astro.url.pathname, locale), Astro.site)}    />    <!-- Hreflang Links -->    {      localeMap(({ locale: mapLocale }) => (        <link          rel="alternate"          hreflang={mapLocale}          href={new URL(            getLocalizedUrl(Astro.url.pathname, mapLocale),            Astro.site          )}        />      ))    }    <link      rel="alternate"      hreflang="x-default"      href={new URL(        getLocalizedUrl(Astro.url.pathname, defaultLocale),        Astro.site      )}    />  </head>  <body>    <main>      <h1 id="greeting">{greeting}</h1>      <p id="description">{description}</p>      <div class="locale-switcher">        <span class="switcher-label">{switchLocale}</span>        <div class="locale-buttons">          {            locales.map((localeItem) => (              <a                href={localeItem === locale ? undefined : getLocalizedUrl(pathWithoutLocale, localeItem)}                class={`locale-btn ${localeItem === locale ? "active" : ""}`}                data-locale={localeItem}                aria-disabled={localeItem === locale}              >                {getLocaleName(localeItem)}              </a>            ))          }        </div>      </div>    </main>  </body></html>
      If you want to use your content in a string attribute, such as alt, title, href, aria-label, etc., you can use the value of the function, like:
      html
      <img src="{content.image.src.value}" alt="{content.image.value}" /><img src="{content.image.src.toString()}" alt="{content.image.toString()}" /><img src="{String(content.image.src)}" alt="{String(content.image)}" />

      Note on routing setup: The directory structure you use depends on the middleware.routing setting in intlayer.config.ts:

      • prefix-no-default (default): keeps the default language at the root (no prefix) and prefixes others. Use [...locale] to catch all cases.
      • prefix-all: all URLs get a language prefix. You can use standard [locale] if you don't need to handle the root separately.
      • search-param or no-prefix: no language directories are needed. The language is handled via query parameters or cookies.
    6. Adding a Language Switcher

      In Astro with Vanilla JS, the language switcher is rendered on the server as regular links and hydrated on the client via a <script> block. When a user clicks a language link, vanilla-intlayer sets the language cookie via setLocale before navigating to the localised URL.

      src/pages/[...locale]/index.astro
      <!-- Include the server-side markup from step 5 above --><script>  import { installIntlayer, useLocale } from "vanilla-intlayer";  import { getLocaleFromPath, getLocalizedUrl, type LocalesValues } from "intlayer";  // Initialise Intlayer on the client with the locale taken from the current path  const locale = getLocaleFromPath(window.location.pathname);  installIntlayer({ locale: locale as LocalesValues });  const { setLocale } = useLocale({    onLocaleChange: (newLocale: LocalesValues) => {      window.location.href = getLocalizedUrl(window.location.pathname, newLocale);    },  });  // Bind click events to language switcher links  const localeLinks = document.querySelectorAll("[data-locale]");  localeLinks.forEach((link) => {    link.addEventListener("click", (e) => {      const localeValue = link.getAttribute("data-locale") as LocalesValues;      if (localeValue && localeValue !== locale) {        e.preventDefault();        setLocale(localeValue);      }    });  });</script>

      Note on persistence: installIntlayer initialises the Intlayer singleton with the server-defined locale. useLocale with onLocaleChange ensures the language cookie is set before navigating via the middleware, so that the user's language preference is remembered in future visits.

      Note on Progressive Enhancement: The links in the language switcher will work as standard <a> tags even without JavaScript. When JavaScript is available, calls to setLocale will update the cookie before navigating, ensuring the middleware performs the correct redirect.

    7. Sitemap and Robots.txt

      Intlayer offers utilities to dynamically create your localised sitemap and robots.txt files.

      Sitemap

      Intlayer comes with a built-in sitemap generator to help you create a sitemap for your application easily. It handles localized routes and adds the necessary metadata for search engines.

      The Intlayer generated sitemap supports the xhtml:link namespace (Hreflang XML Extensions). Unlike the default sitemap generators that only list raw URLs, Intlayer automatically creates the required bidirectional links between all language versions of a page (e.g., /about, /about?lang=fr, and /about?lang=es). This ensures search engines correctly index and serve the right language version to the right audience.

      Create src/pages/sitemap.xml.ts to generate a sitemap including all your localised routes.

      src/pages/sitemap.xml.ts
      import type { APIRoute } from "astro";import { generateSitemap, type SitemapUrlEntry } from "intlayer";const pathList: SitemapUrlEntry[] = [  { path: "/", changefreq: "daily", priority: 1.0 },  { path: "/about", changefreq: "monthly", priority: 0.7 },];const SITE_URL = import.meta.env.SITE ?? "http://localhost:4321";export const GET: APIRoute = async ({ site }) => {  const xmlOutput = generateSitemap(pathList, { siteUrl: SITE_URL });  return new Response(xmlOutput, {    headers: { "Content-Type": "application/xml" },  });};

      Robots.txt

      Create src/pages/robots.txt.ts to control search engine crawling.

      src/pages/robots.txt.ts
      import type { APIRoute } from "astro";import { getMultilingualUrls } from "intlayer";const getAllMultilingualUrls = (urls: string[]) =>  urls.flatMap((url) => Object.values(getMultilingualUrls(url)) as string[]);const disallowedPaths = getAllMultilingualUrls(["/admin", "/private"]);export const GET: APIRoute = ({ site }) => {  const robotsTxt = [    "User-agent: *",    "Allow: /",    ...disallowedPaths.map((path) => `Disallow: ${path}`),    "",    `Sitemap: ${new URL("/sitemap.xml", site).href}`,  ].join("\n");  return new Response(robotsTxt, {    headers: { "Content-Type": "text/plain" },  });};
    8. Extract the content of your components

      Optional

      If you have an existing codebase, transforming thousands of files can be time-consuming.

      To ease this process, Intlayer propose a compiler / extractor to transform your components and extract the content.

      To set it up, you can add a compiler section in your intlayer.config.ts file:

      intlayer.config.ts
      import { type IntlayerConfig } from "intlayer";
      
      const config: IntlayerConfig = {
        // ... Rest of your config
        compiler: {
          /**
           * Indicates if the compiler should be enabled.
           */
          enabled: true,
      
          /**
           * Defines the output files path
           */
          output: ({ fileName, extension }) => `./${fileName}${extension}`,
      
          /**
           * Indicates if the components should be saved after being transformed.
           *
           * - If `true`, the compiler will rewrite the component file in the disk. So the transformation will be permanent, and the compiler will skip the transformation for the next process. That way, the compiler can transform the app, and then it can be removed.
           *
           * - If `false`, the compiler will inject the `useIntlayer()` function call into the code in the build output only, and keep the base codebase intact. The transformation will be done only in memory.
           */
          saveComponents: false,
      
          /**
           * Dictionary key prefix
           */
          dictionaryKeyPrefix: "",
        },
      };
      
      export default config;

      Run the extractor to transform your components and extract the content

      bash
      npx intlayer extract

    TypeScript Configuration

    Intlayer uses module augmentation to leverage TypeScript, making your codebase more robust.

    Autocompletion

    Translation Error

    Ensure your TypeScript configuration includes the autogenerated types.

    tsconfig.json
    {  // ... your existing TypeScript configuration  "include": [    // ... your existing TypeScript configuration    ".intlayer/**/*.ts", // Include autogenerated types  ],}

    Git Configuration

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

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

    bash
    # Ignore the files generated by Intlayer.intlayer

    VS Code Extension

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

    Installation from the VS Code Marketplace

    This extension provides:

    • Autocompletion for translation keys.
    • Real-time error detection for missing translations.
    • Inline preview of translated content.
    • Quick actions for easily creating and updating translations.

    For more information on using the extension, refer to the VS Code Extension documentation.


    Deepen Your Knowledge

    If you want to learn more, you can also implement the Visual Editor or use the CMS to externalise your content.