Ask your question and get a summary of the document by referencing this page and the AI provider of your choice
Version History
- "Update Solid useIntlayer API usage to direct property access"v8.9.05/4/2026
- "Initial documentation for Astro + Vanilla JS"v8.7.74/24/2026
If you have an idea for improving this documentation, please feel free to contribute by submitting a pull request on GitHub.
GitHub link to the documentationCopy doc Markdown to clipboard
Translate your Astro + Vanilla JS website using Intlayer | Internationalization (i18n)
Table of Contents
What is Intlayer?
Intlayer is an innovative, open-source internationalization (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 localize 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.
Step-by-Step Guide to Set Up Intlayer in Astro + Vanilla JS
See Application Template on GitHub.
Step 1: Install Dependencies
Install the necessary packages using your package manager:
Copy the code to the clipboard
npm install intlayer astro-intlayer vanilla-intlayernpx intlayer initintlayer The core package that provides internationalization tools for configuration management, translation, content declaration, transpilation, and CLI commands.
astro-intlayer Includes the Astro integration 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.
vanilla-intlayer The package that integrates Intlayer with plain JavaScript / TypeScript applications. It provides a pub/sub singleton (
IntlayerClient) and callback-based helpers (useIntlayer,useLocale, etc.) so any part of your Astro<script>blocks can react to locale changes without a UI framework.
Step 2: Configuration of your project
Create a config file to configure the languages of your application:
Copy the code to the clipboard
import { Locales, type IntlayerConfig } from "intlayer";const config: IntlayerConfig = { internationalization: { locales: [ Locales.ENGLISH, Locales.FRENCH, Locales.SPANISH, // Your other locales ], defaultLocale: Locales.ENGLISH, },};export default config;Through this configuration file, you can set up localized 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 3: Integrate Intlayer in Your Astro Configuration
Add the intlayer plugin into your configuration. No extra UI-framework integration is needed for Vanilla JS.
Copy the code to the clipboard
// @ts-checkimport { intlayer } from "astro-intlayer";import { defineConfig } from "astro/config";// https://astro.build/configexport default defineConfig({ integrations: [intlayer()],});The intlayer() Astro integration plugin is used to integrate Intlayer with Astro. It ensures the building of content declaration files and monitors them in development mode. It defines Intlayer environment variables within the Astro application. Additionally, it provides aliases to optimize performance.
Step 4: Declare Your Content
Create and manage your content declarations to store translations:
Copy the code to the clipboard
import { t, type Dictionary } from "intlayer";const appContent = { key: "app", content: { greeting: t({ en: "Hello World", fr: "Bonjour le monde", es: "Hola mundo", }), description: t({ en: "Welcome to my multilingual Astro site.", fr: "Bienvenue sur mon site Astro multilingue.", es: "Bienvenido a mi sitio Astro multilingüe.", }), switchLocale: t({ en: "Switch language:", fr: "Changer de langue :", es: "Cambiar idioma:", }), },} satisfies Dictionary;export default appContent;Your content declarations can be defined anywhere in your application as soon they are included into thecontentDirdirectory (by default,./src). And match the content declaration file extension (by default,.content.{json,ts,tsx,js,jsx,mjs,cjs}).
For more details, refer to the content declaration documentation.
Step 5: Use your content in Astro
With Vanilla JS, all rendering is done directly in the .astro file using getIntlayer for the initial server render. A <script> block then bootstraps vanilla-intlayer on the client side for locale switching.
Copy the code to the clipboard
---import { getIntlayer, getLocaleFromPath, getLocalizedUrl, getPrefix, getLocaleName, localeMap, locales, defaultLocale, getPathWithoutLocale, getHTMLTextDir, 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 astringattribute, such asalt,title,href,aria-label, etc., you can use the value of the function, like:
htmlCopy codeCopy the code to the clipboard
<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 Configuration: The directory structure you use depends on the
middleware.routingsetting in yourintlayer.config.ts:
prefix-no-default(default): Keeps the default locale at the root (no prefix) and prefixes others. Use[...locale]to catch all cases.prefix-all: All URLs are prefixed with the locale. You can use standard[locale]if you don't need to handle the root separately.search-paramorno-prefix: No locale folder is needed. The locale is handled via search parameters or cookies.
Step 6: Add a Locale Switcher
With Vanilla JS in Astro, the locale switcher is rendered server-side as anchor links and hydrated on the client via a <script> block. When the user clicks a locale link, vanilla-intlayer sets the locale cookie via setLocale before navigating to the localized URL.
Copy the code to the clipboard
<!-- server-side markup shown in Step 5 above --><script> import { installIntlayer, useLocale } from "vanilla-intlayer"; import { getLocaleFromPath, getLocalizedUrl, type LocalesValues } from "intlayer"; // Bootstrap Intlayer on the client using the current URL's locale 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); }, }); // Attach click handlers to locale anchor 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:
installIntlayerbootstraps the Intlayer singleton with the server-detected locale.useLocalewithonLocaleChangethen sets the locale cookie via the middleware before navigating, so the user's preference is remembered on future visits.
Note on Progressive Enhancement: The locale links work as standard
<a>tags even without JavaScript. When JS is available, thesetLocalecall updates the cookie before the navigation so the middleware can redirect correctly.
Step 7: Sitemap and Robots.txt
Intlayer provides utilities to generate localized sitemaps and robots.txt files dynamically.
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 thexhtml:linknamespace (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 that includes all your localized routes.
Copy the code to the clipboard
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.
Copy the code to the clipboard
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" }, });};Configure TypeScript
Intlayer use module augmentation to get benefits of TypeScript and make your codebase stronger.


Ensure your TypeScript configuration includes the autogenerated types.
Copy the code to the clipboard
{ // ... Your existing TypeScript configurations include: [ // ... Your existing TypeScript configurations ".intlayer/**/*.ts", // Include the auto-generated types ],}Git Configuration
It is recommended to ignore the files generated by Intlayer. This allows you to avoid committing them to your Git repository.
To do this, you can add the following instructions to your .gitignore file:
Copy the code to the clipboard
# Ignore the files generated by Intlayer.intlayerVS 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.
(Optional) Step 15: Extract the content of your components
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:
Copy the code to the clipboard
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
Copy the code to the clipboard
npx intlayer extractGo Further
To go further, you can implement the visual editor or externalize your content using the CMS.