withastro/astro
Internationalization (i18n)
Astro's built-in localization system: route prefixes per locale, default-locale fallbacks, and a typed helper to resolve URLs across locales.
Purpose
Serve the same content under multiple URLs (one per locale), gracefully fall back when a translation is missing, and let user code reason about the active locale at render time.
Key files
| File | Purpose |
|---|---|
packages/astro/src/i18n/index.ts |
Public helpers (getLocaleByPath, getRelativeLocaleUrl, etc.). |
packages/astro/src/i18n/router.ts |
Locale-aware route matching. |
packages/astro/src/i18n/middleware.ts |
The middleware Astro inserts when i18n is configured. |
packages/astro/src/i18n/fallback.ts |
Per-locale fallback chain. |
packages/astro/src/i18n/utils.ts |
Locale parsing, normalization. |
packages/astro/src/i18n/vite-plugin-i18n.ts |
Emits the astro:i18n virtual module. |
packages/astro/src/core/config/schemas/base.ts |
i18n config schema (locales, defaults, routing strategy). |
Routing strategies
The user picks one in astro.config.mjs:
i18n: {
defaultLocale: 'en',
locales: ['en', 'fr', 'pt-br'],
routing: { prefixDefaultLocale: false }, // or `manual`
}| Strategy | Result |
|---|---|
prefixDefaultLocale: false |
/about is English, /fr/about is French. |
prefixDefaultLocale: true |
All locales prefixed: /en/about, /fr/about. |
routing: 'manual' |
The router only inserts the i18n middleware; user code resolves locales explicitly. |
How it works
graph TD
A[Request URL] --> B[i18n middleware]
B -->|Detect locale| C{Locale in URL?}
C -- yes --> D[Set Astro.currentLocale]
C -- no --> E{Manual?}
E -- no --> F[Redirect to default locale URL]
E -- yes --> D
D --> G[Match route]
G --> H{Page exists for locale?}
H -- no --> I[Try fallback locale]
I --> H
H -- yes --> J[Render page]The fallback chain (packages/astro/src/i18n/fallback.ts) supports any DAG-like configuration — for example, "fr-CA falls back to fr, fr falls back to en". The astro:routes:resolved event includes the synthesized fallback routes so @astrojs/sitemap can include them (feat: Add fallbackRoutes…, commit babf57f).
Public helpers
astro:i18n exposes:
getRelativeLocaleUrl(locale, path?)getAbsoluteLocaleUrl(locale, path?)getRelativeLocaleUrlList(path?)getAbsoluteLocaleUrlList(path?)getPathByLocale(locale)redirectToDefaultLocale()(manual mode)redirectToFallback()(manual mode)notFound()(manual mode)
Astro.currentLocale is exposed on every render context.
Tests
packages/astro/test/units/i18n/astro_i18n.test.ts (1,786 lines) and manual-routing.test.ts (1,350 lines) are two of the largest test files in the repo, indicative of how many strategy/fallback combinations are kept honest.
Related pages
Built by Factory AutoWiki from public repository content. It is a generated preview for codebase exploration, not source-maintained documentation.