Astro i18n routing is built in: add an i18n block to astro.config.mjs with your locales and defaultLocale, put translated pages in folders named after each locale (src/pages/es/, src/pages/fr/), and Astro handles the URL prefixes, fallbacks and Astro.currentLocale. Translating the actual words is still your job; Astro routes the languages, it does not translate them.
This guide walks through the config, folder layout, URL strategies, the astro:i18n helper functions, a language switcher, hreflang tags and translated content collections, all for Astro 7.
Key Takeaways
i18n.localesandi18n.defaultLocaleare the only required options.- With the default
prefixDefaultLocale: false, English lives at/about/and Spanish at/es/about/.- Use
getRelativeLocaleUrl()fromastro:i18ninstead of hand-building localized links.fallbacksends missing translations to another locale, by redirect or by rewrite.- Astro does not add
hreflangtags for you. Render them in your layout.
Configure Astro i18n
Start with the two required options. Locale codes are free-form, but lowercase codes with hyphens (en, es, pt-br) are the safest choice because they become folder names and URL segments.
// astro.config.mjs
import { defineConfig } from 'astro/config';
export default defineConfig({
site: 'https://www.example.com',
i18n: {
locales: ['en', 'es', 'fr'],
defaultLocale: 'en',
},
});
The defaultLocale must be one of the locales. Set site too, because the absolute URL helpers and hreflang tags need it. The full option list is in the Astro i18n routing guide and the configuration reference.
Folder structure for translated pages
With the config above and no routing options, the default locale has no prefix. Pages for other locales live in a folder that matches the locale code exactly:
src/pages/
index.astro -> /
about.astro -> /about/
es/
index.astro -> /es/
about.astro -> /es/about/
fr/
index.astro -> /fr/
about.astro -> /fr/about/
Folder names must match the locales entries character for character. A folder called ES or es-es will not be treated as the es locale. If you are new to file-based routing, pages and routing in a theme and the Astro routing guide cover the basics this builds on.
Inside any page, Astro.currentLocale returns the locale for the current route, so a shared layout can set <html lang> correctly:
---
// src/layouts/BaseLayout.astro
const lang = Astro.currentLocale ?? 'en';
---
<html lang={lang}>
<body><slot /></body>
</html>
Choosing a URL strategy
The routing object controls prefixes. There are two common setups and one advanced one.
| Setup | Config | English URL | Spanish URL |
|---|---|---|---|
| No prefix for default (default) | prefixDefaultLocale: false |
/about/ |
/es/about/ |
| Prefix every locale | prefixDefaultLocale: true |
/en/about/ |
/es/about/ |
| Domain per locale | domains + server output |
example.com/about/ |
example.es/about/ |
Keeping the default unprefixed is the right choice when you add languages to an existing site, because your current URLs do not move. Prefixing every locale is cleaner when no language is primary, and it makes the folder structure symmetrical:
// astro.config.mjs
export default defineConfig({
site: 'https://www.example.com',
i18n: {
locales: ['en', 'es', 'fr'],
defaultLocale: 'en',
routing: {
prefixDefaultLocale: true,
redirectToDefaultLocale: true,
},
},
});
With prefixDefaultLocale: true, English pages move into src/pages/en/. Keep a src/pages/index.astro for the root; with redirectToDefaultLocale: true, Astro redirects / to /en/. Both options default to false.
The domains option maps a locale to its own domain or subdomain. It requires output: 'server' with an adapter and no prerendered pages, so it is a poor fit for static sites. For most projects, path prefixes are simpler to host and to track in analytics.
You can also set routing: 'manual' to switch off Astro’s automatic i18n middleware and compose your own with the middleware() helper from astro:i18n. Reach for that only when you need custom logic, such as reading a locale cookie.
Linking between locales with astro:i18n
Hard-coding /es/ into links breaks the moment you change the prefix strategy or add a base. The astro:i18n module builds URLs from your config:
---
// src/components/LocalizedNav.astro
import { getRelativeLocaleUrl } from 'astro:i18n';
const locale = Astro.currentLocale ?? 'en';
---
<nav>
<a href={getRelativeLocaleUrl(locale, '')}>Home</a>
<a href={getRelativeLocaleUrl(locale, 'about')}>About</a>
<a href={getRelativeLocaleUrl(locale, 'blog')}>Blog</a>
</nav>
The module exports a small set of helpers you will use often:
getRelativeLocaleUrl(locale, path)returns a path such as/es/about/.getAbsoluteLocaleUrl(locale, path)returns a full URL usingsite, useful for canonicals andhreflang.getRelativeLocaleUrlList(path)andgetAbsoluteLocaleUrlList(path)return the URL for every locale at once.getLocaleByPath(path)andgetPathByLocale(locale)convert between custom paths and locale codes.
These helpers respect trailingSlash, base and prefixDefaultLocale, so links stay correct when the config changes.
A language switcher
A switcher should keep the visitor on the same page in the other language, not dump them on the home page. Strip the current locale prefix from the path and rebuild it for each target:
---
// src/components/LanguageSwitcher.astro
import { getRelativeLocaleUrl } from 'astro:i18n';
const labels: Record<string, string> = { en: 'English', es: 'Español', fr: 'Français' };
const current = Astro.currentLocale ?? 'en';
// Remove a leading /es/ or /fr/ so we have the locale-neutral path.
const segments = Astro.url.pathname.split('/').filter(Boolean);
if (segments[0] && segments[0] in labels) segments.shift();
const path = segments.join('/');
---
<ul aria-label="Language">
{Object.entries(labels).map(([code, label]) => (
<li>
<a
href={getRelativeLocaleUrl(code, path)}
hreflang={code}
lang={code}
aria-current={code === current ? 'true' : undefined}
>
{label}
</a>
</li>
))}
</ul>
This assumes translated pages share the same slug in every language (/about/, /es/about/). If you translate slugs (/es/acerca/), keep a map of equivalent paths and look the target up there instead.
Fallbacks for missing translations
Translations rarely land all at once. The fallback option tells Astro which locale to serve when a page does not exist in the requested one:
// astro.config.mjs
export default defineConfig({
i18n: {
locales: ['en', 'es', 'fr'],
defaultLocale: 'en',
fallback: { es: 'en', fr: 'en' },
routing: {
prefixDefaultLocale: false,
fallbackType: 'rewrite',
},
},
});
With fallbackType: 'redirect' (the default), a visitor to /fr/pricing/ with no French page is redirected to /pricing/. With 'rewrite', the build writes /fr/pricing/ containing the English content, so the URL stays in French. Rewrites feel smoother, but they publish duplicate content under two URLs; point the canonical of the fallback page at the original language to avoid that. Without a fallback entry, missing pages return a 404.
hreflang tags and the sitemap
Search engines need hreflang alternates to understand which page is the Spanish version of which English page. Astro does not add them, so render them once in the base layout:
---
// src/components/Hreflang.astro
import { getAbsoluteLocaleUrl } from 'astro:i18n';
const locales = ['en', 'es', 'fr'];
const current = Astro.currentLocale ?? 'en';
const prefix = current === 'en' ? '' : `/${current}`;
const path = Astro.url.pathname.replace(prefix, '').replace(/^\//, '');
---
{locales.map((code) => (
<link rel="alternate" hreflang={code} href={getAbsoluteLocaleUrl(code, path)} />
))}
<link rel="alternate" hreflang="x-default" href={getAbsoluteLocaleUrl('en', path)} />
Only output alternates for pages that actually exist in each language; an hreflang pointing at a redirect or a 404 is ignored by search engines. The @astrojs/sitemap integration also accepts an i18n option (defaultLocale plus a locales map of codes to language tags) and adds alternate links to the sitemap. Combine that with the canonical rules in the Astro canonical URLs tip.
Translating UI strings and content
Routing gives you /es/ pages; you still need Spanish words in them. Keep interface strings in a small dictionary:
// src/i18n/ui.ts
export const ui = {
en: { 'nav.home': 'Home', 'nav.blog': 'Blog', 'post.readMore': 'Read more' },
es: { 'nav.home': 'Inicio', 'nav.blog': 'Blog', 'post.readMore': 'Leer más' },
fr: { 'nav.home': 'Accueil', 'nav.blog': 'Blog', 'post.readMore': 'Lire la suite' },
} as const;
export function t(locale: string | undefined, key: keyof (typeof ui)['en']) {
const lang = (locale ?? 'en') as keyof typeof ui;
return ui[lang]?.[key] ?? ui.en[key];
}
For long-form content, store each language in its own folder inside a content collection (src/content/blog/en/, src/content/blog/es/) and filter by the folder prefix of the entry id in getStaticPaths(). That keeps one schema for every language and lets you generate /es/blog/[slug]/ from the same collection. The Content Collections guide covers loaders and schemas in depth.
If you are building a multilingual site for a client, a finished theme gives you the layouts and components to localize; Astro themes by category is a quick way to find one close to the site you need.
FAQ
Does Astro translate my content automatically?
No. Astro i18n handles routing, locale detection and URL helpers. You write or source the translated text yourself, either as separate pages, separate content entries, or a dictionary of UI strings.
Can Astro i18n routing work on a fully static site?
Yes. Locale folders, prefixes, fallbacks with redirect or rewrite, and the astro:i18n helpers all work with static output. Only the domains option needs server output and an adapter.
How do I detect the visitor’s browser language in Astro?
Astro.preferredLocale and Astro.preferredLocaleList read the Accept-Language header and match it against your locales. They need a page rendered on demand, because a prerendered page has no request headers at build time.
Should the default language have a URL prefix?
Keep it unprefixed if you are adding languages to an existing site, so current URLs and rankings stay put. Prefix every locale if no language is primary or you want identical folder structures for each one.
How do I add hreflang tags in Astro?
Render <link rel="alternate" hreflang="..."> tags in your base layout, using getAbsoluteLocaleUrl() from astro:i18n to build each URL, and add an x-default entry for the default language.