# Translate your Astro + Lit website using Intlayer | Internationalization (i18n)
## 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 + Lit
See [Application Template](https://github.com/aymericzip/intlayer-astro-template) on GitHub.
### Step 1: Install Dependencies
Install the necessary packages using your package manager:
```bash packageManager="npm"
npm install intlayer astro-intlayer lit lit-intlayer @astrojs/lit
npx intlayer init
```
```bash packageManager="pnpm"
pnpm add intlayer astro-intlayer lit lit-intlayer @astrojs/lit
pnpm intlayer init
```
```bash packageManager="yarn"
yarn add intlayer astro-intlayer lit lit-intlayer @astrojs/lit
yarn intlayer init
```
```bash packageManager="bun"
bun add intlayer astro-intlayer lit lit-intlayer @astrojs/lit
bun x intlayer init
```
- **intlayer**
The core package that provides internationalization tools for configuration management, translation, [content declaration](https://github.com/aymericzip/intlayer/blob/main/docs/docs/en/dictionary/content_file.md), transpilation, and [CLI commands](https://github.com/aymericzip/intlayer/blob/main/docs/docs/en/cli/index.md).
- **astro-intlayer**
Includes the Astro integration plugin for integrating Intlayer with the [Vite bundler](https://vite.dev/guide/why.html#why-bundle-for-production), as well as middleware for detecting the user's preferred locale, managing cookies, and handling URL redirection.
- **lit**
The core Lit package for building fast, lightweight Web Components.
- **lit-intlayer**
The package that integrates Intlayer with Lit applications. It provides `ReactiveController`-based hooks (`useIntlayer`, `useLocale`, etc.) so that LitElements automatically re-render when the locale changes.
- **@astrojs/lit**
The official Astro integration that enables Lit custom elements in Astro pages.
### Step 2: Configuration of your project
Create a config file to configure the languages of your application:
```typescript fileName="intlayer.config.ts"
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](https://github.com/aymericzip/intlayer/blob/main/docs/docs/en/configuration.md).
### Step 3: Integrate Intlayer in Your Astro Configuration
Add the intlayer plugin and the Lit integration into your configuration.
```typescript fileName="astro.config.ts"
// @ts-check
import { intlayer } from "astro-intlayer";
import lit from "@astrojs/lit";
import { defineConfig } from "astro/config";
// https://astro.build/config
export default defineConfig({
integrations: [intlayer(), lit()],
});
```
> 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.
> The `lit()` integration enables Lit custom elements in Astro pages.
### Step 4: Declare Your Content
Create and manage your content declarations to store translations:
```typescript fileName="src/components/lit/app.content.ts"
import { t, type Dictionary } from "intlayer";
const litDemoContent = {
key: "lit-demo",
content: {
greeting: t({
en: "Hello World",
fr: "Bonjour le monde",
es: "Hola mundo",
}),
description: t({
en: "Welcome to my multilingual Astro + Lit site.",
fr: "Bienvenue sur mon site Astro + Lit multilingue.",
es: "Bienvenido a mi sitio Astro + Lit multilingüe.",
}),
},
} satisfies Dictionary;
export default litDemoContent;
```
> Your content declarations can be defined anywhere in your application as soon they are included into the `contentDir` directory (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](https://github.com/aymericzip/intlayer/blob/main/docs/docs/en/dictionary/content_file.md).
### Step 5: Use your content in Astro
You can consume dictionaries directly in `.astro` files using the core helpers exported by `intlayer`. You should also add SEO metadata like hreflang and canonical links to each page. The Lit custom element is then imported via a client-side `
```
> 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
>
>
>
> ```
> **Note on Routing Configuration:**
> The directory structure you use depends on the `middleware.routing` setting in your `intlayer.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-param` or `no-prefix`:** No locale folder is needed. The locale is handled via search parameters or cookies.
### Step 6: Create the Lit custom element
Create the Lit custom element. `installIntlayer` is called in `connectedCallback` with the server-detected `locale` property to initialize the Intlayer singleton on the client.
```typescript fileName="src/components/lit/LitDemo.ts"
import { LitElement, html } from "lit";
import { installIntlayer, useIntlayer, useLocale } from "lit-intlayer";
import { getLocalizedUrl, getLocaleName, type LocalesValues } from "intlayer";
class LitDemo extends LitElement {
static properties = {
locale: { type: String },
};
locale: LocalesValues = "en" as LocalesValues;
private _content = useIntlayer(this, "lit-demo");
private _localeCtrl = useLocale(this, {
onLocaleChange: (newLocale: LocalesValues) => {
window.location.href = getLocalizedUrl(
window.location.pathname,
newLocale,
);
},
});
override connectedCallback() {
super.connectedCallback();
// Initialize with the server-detected locale
installIntlayer({ locale: this.locale as any });
}
override render() {
const { greeting, description } = this._content;
const {
locale: currentLocale,
availableLocales,
setLocale,
} = this._localeCtrl;
return html`
`;
}
}
customElements.define("lit-demo", LitDemo);
```
> The `locale` property is passed from the Astro page (server-detected) and used in `connectedCallback` to initialise `installIntlayer`, making it the initial locale for all `ReactiveController` hooks in the element.
> `useIntlayer` registers itself as a `ReactiveController`. The element re-renders automatically when the locale changes — no extra setup required.
### Step 7: Add a Locale Switcher
The locale switcher is embedded directly in the Lit custom element's `render()` method (shown in Step 6). It uses `useLocale` from `lit-intlayer` and navigates to the localized URL when the user picks a new language:
```typescript fileName="src/components/lit/LitDemo.ts"
// Within the LitElement class, after useLocale setup (shown in Step 6):
private _localeCtrl = useLocale(this, {
onLocaleChange: (newLocale: LocalesValues) => {
// Navigate to the localized URL on locale change
window.location.href = getLocalizedUrl(window.location.pathname, newLocale);
},
});
override render() {
const { locale: currentLocale, availableLocales, setLocale } = this._localeCtrl;
return html`
`;
}
```
> **Note on Lit Reactivity:**
> `useLocale` returns a `ReactiveController`. When `setLocale` is called, the controller schedules a re-render automatically — so the active button state updates without manual DOM manipulation.
> **Note on Persistence:**
> Using `onLocaleChange` to redirect via `window.location.href` ensures that the new locale URL is visited, allowing Intlayer middleware to set the locale cookie and remember the user's preference on future visits.
### Step 8: 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 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 that includes all your localized routes.
```typescript fileName="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.
```typescript fileName="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" },
});
};
```
### Configure TypeScript
Intlayer use module augmentation to get benefits of TypeScript and make your codebase stronger. Lit requires `experimentalDecorators` to be enabled if you use the decorator syntax.


Ensure your TypeScript configuration includes the autogenerated types.
```json5 fileName="tsconfig.json"
{
compilerOptions: {
// ...
experimentalDecorators: true,
useDefineForClassFields: false, // Required by Lit for decorator support
},
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:
```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**.
[Install from the VS Code Marketplace](https://marketplace.visualstudio.com/items?itemName=intlayer.intlayer-vs-code-extension)
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](https://intlayer.org/doc/vs-code-extension).
---
### (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](https://github.com/aymericzip/intlayer/blob/main/docs/docs/en/compiler.md) / [extractor](https://github.com/aymericzip/intlayer/blob/main/docs/docs/en/cli/extract.md) to transform your components and extract the content.
To set it up, you can add a `compiler` section in your `intlayer.config.ts` file:
```typescript fileName="intlayer.config.ts" codeFormat={["typescript", "esm", "commonjs"]}
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 packageManager="npm"
npx intlayer extract
```
```bash packageManager="pnpm"
pnpm intlayer extract
```
```bash packageManager="yarn"
yarn intlayer extract
```
```bash packageManager="bun"
bun x intlayer extract
```
Update your `vite.config.ts` to include the `intlayerCompiler` plugin:
```ts fileName="vite.config.ts"
import { defineConfig } from "vite";
import { intlayer, intlayerCompiler } from "vite-intlayer";
export default defineConfig({
plugins: [
intlayer(),
intlayerCompiler(), // Adds the compiler plugin
],
});
```
```bash packageManager="npm"
npm run build # Or npm run dev
```
```bash packageManager="pnpm"
pnpm run build # Or pnpm run dev
```
```bash packageManager="yarn"
yarn build # Or yarn dev
```
```bash packageManager="bun"
bun run build # Or bun run dev
```
---
### Go Further
To go further, you can implement the [visual editor](https://github.com/aymericzip/intlayer/blob/main/docs/docs/en/intlayer_visual_editor.md) or externalize your content using the [CMS](https://github.com/aymericzip/intlayer/blob/main/docs/docs/en/intlayer_CMS.md).