#How to switch languages with Astro?
1 messages · Page 1 of 1 (latest)
Hi @honest tapir. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
Switching Languages in Astro
There are two main approaches depending on whether you're using Astro's built-in i18n or a manual setup.
1. Manual i18n Setup (Link-based Language Picker)
You can create a LanguagePicker component that renders a link for each supported language: [i18n recipe]
---
// src/components/LanguagePicker.astro
import { languages } from '../i18n/ui';
---
<ul>
{Object.entries(languages).map(([lang, label]) => (
<li>
<a href={`/${lang}/`}>{label}</a>
</li>
))}
</ul>
Then add it to your base layout so it appears on every page.
2. Select Menu Language Switcher
To use a <select> menu instead of links, you can adapt the same approach with a small JavaScript handler:
---
// src/components/LanguagePicker.astro
import { languages } from '../i18n/ui';
import { getLangFromUrl } from '../i18n/utils';
const lang = getLangFromUrl(Astro.url);
---
<select onchange="window.location.href = this.value">
{Object.entries(languages).map(([l, label]) => (
<option value={`/${l}/`} selected={l === lang}>
{label}
</option>
))}
</select>
This uses window.location.href to navigate to the selected language's root path when the user picks an option.
3. With Translated Paths
If you also translate your route paths (e.g. /fr/prestations-de-service), use the useTranslatedPath helper to generate the correct URL per language: [translated paths]
---
import { languages } from '../i18n/ui';
import { getLangFromUrl, useTranslatedPath } from '../i18n/utils';
const lang = getLangFromUrl(Astro.url);
const translatePath = useTranslatedPath(lang);
<select onchange="window.location.href = this.value">
{Object.entries(languages).map(([l, label]) => (
<option value={translatePath('/', l)} selected={l === lang}>
{label}
</option>
))}
</select>
---
### 4. Starlight (if using the docs framework)
If you're using Astro's **Starlight** documentation framework, a `LanguageSelect` component is built in and rendered automatically in the header when you configure `locales`. [[Starlight i18n](<https://starlight.astro.build/guides/i18n/#configure-i18n>)] [[Starlight overrides](<https://starlight.astro.build/reference/overrides/#languageselect>)]
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------