On this page
Astro is the static-first web framework for content-driven sites: file-based routing, zero JavaScript by default, "islands" for opt-in interactivity, an SSR-on-demand mode for the parts that need it. Since v4.0 (late 2023, stable in v5+, current in v7.x), Astro ships built-in i18n routing: URL prefixing (/en/, /de/), the Astro.currentLocale helper, browser-language detection, and URL helpers such as getRelativeLocaleUrl.
What Astro's built-in i18n does not provide is a translation function (t()), pluralization, or message interpolation. Astro's official i18n recipe shows a "build it yourself" pattern: import a per-locale JSON file and write a small lookup helper. That covers plain strings, and stops where plurals, interpolation and fallbacks begin. i18next fills that gap, at build time: it runs while Astro renders the pages, so a static build still sends no JavaScript to the browser. Locize manages the translations: locize-cli downloads the latest published JSON into src/i18n/locales/{lng}/{ns}.json before the build, and i18next reads those files.
This post walks the integration end-to-end. The complete code lives at github.com/locize/locize-astro-example.
Updated 2026-11-17: the first version of this post used a hand-written
t()helper. It now uses i18next, which adds plurals, interpolation in the i18next JSON format Locize uses by default, and fallbacks, still without JavaScript in the browser. The example moved to Astro 7.
If you're on Nuxt instead, follow the Nuxt 4 walkthrough. If you're on React Router v7 (framework mode), see the React Router v7 walkthrough. Both cover richer integrations (in-context editor, runtime saveMissing) that don't fit Astro's static-by-default model directly.
TL;DR
- Configure Astro's built-in i18n routing in
astro.config.mjs: locale list +prefixDefaultLocale: truefor uniform URLs. - Use dynamic
[lang]/page routes withgetStaticPathsso every locale is statically pre-rendered. - Sync translations into the app at build time via
locize-cli'sdownloadcommand. No runtime CDN hop, no SSR considerations. - Load the downloaded files into i18next once in
src/i18n/index.ts; each page gets at()for its language withgetFixedT. In a static build i18next only runs at build time, so no JavaScript goes to the browser. - Write the
<link rel="alternate" hreflang>tags in your layout: Astro's routing does not add them. - Land new keys via
npm run syncLocalesor the Locize web app, whichever fits your workflow. No runtimesaveMissingis possible from the static layer. - Need runtime saveMissing, live CDN fetch, or the in-context editor? Mount any React/Vue/Svelte island via
@astrojs/<framework>and usei18next-locize-backend+ thelocizepackage inside the island. - Full working example: github.com/locize/locize-astro-example
How the pieces fit
Astro is static-by-default. Pages are pre-rendered to HTML at build time and served as static files (or, in SSR mode, via an adapter on demand). Astro's built-in i18n owns the routing layer (URL prefixing, locale-aware redirects, browser detection helpers) but deliberately stays out of the message-translation layer. That's why every Astro i18n tutorial ends with "now write your own t() helper". i18next is that layer, ready-made.
Locize is the translation management layer. The integration is bundle-only at runtime:
- Build time:
locize-clidownloads the latest published JSON from the Locize CDN intosrc/i18n/locales/{lng}/{ns}.json.src/i18n/index.tsloads every file found there into i18next. t()is i18next, called while Astro renders each page: plurals, interpolation, fallback to the default language, one namespace per file. In a static build none of it reaches the browser: the output is plain HTML.- Updates require a rebuild, same as any other Astro content change. Run
npm run downloadLocalesand redeploy.
That last point is the trade-off. A "translation published in Locize → end users see it" round trip means re-running the build. If you'd rather have live CDN-backed fetch (publish → next page view picks it up, no redeploy), you mount a framework island and use i18next-locize-backend inside it; the React Router v7 walkthrough covers that shape, and you can adopt the same pattern per-island in Astro. We'll come back to this at the end.
Let's get into it
Prerequisites
Node.js 22.23.4+ (Astro 7 requires it), npm/pnpm/yarn, and basic familiarity with Astro. The example below targets Astro 7.4 and i18next 27.
Project layout
Scaffold a fresh Astro app, or git clone the example:
npm create astro@latest my-app
cd my-appThe relevant directory shape after we wire i18n + Locize:
my-app/
├── astro.config.mjs # Astro's built-in i18n config
├── package.json # locize-cli download/sync scripts
└── src/
├── pages/
│ ├── index.astro # root /, redirects to /en/
│ └── [lang]/
│ ├── index.astro # home, renders for each locale via getStaticPaths
│ └── second.astro # secondary page, same pattern
├── layouts/
│ └── Layout.astro # shared <html>/<head>/<body>
├── components/
│ └── LanguagePicker.astro # swaps the /{lang}/ prefix
└── i18n/
├── index.ts # loads the JSON into i18next; getT + pathForLang
└── locales/ # locize-cli download target (one JSON per ns)
├── en/
│ ├── common.json
│ ├── index.json
│ └── second.json
└── de/
├── common.json
├── index.json
└── second.jsonInstall dependencies
npm install astro i18next
npm install --save-dev locize-cliNo Astro integration package is needed: plain i18next works in .astro files. It is the only runtime dependency, and in a static build it only runs while the site is built.
Configure Astro's built-in i18n in astro.config.mjs
import { defineConfig } from 'astro/config'
export default defineConfig({
site: 'https://example.com', // your domain: the hreflang links need absolute URLs
i18n: {
defaultLocale: 'en',
locales: ['en', 'de'],
routing: {
prefixDefaultLocale: true // /en/, /de/ # uniform URLs
}
}
})Astro now owns:
- URL routing for every page under
src/pages/[lang]/:/en/,/de/,/en/second,/de/second, etc. Astro.currentLocaleavailable in every page/component for free.- Browser-language detection via
Astro.preferredLocaleandAstro.preferredLocaleList(SSR/on-demand routes only).
With prefixDefaultLocale: true, every locale gets a URL prefix: uniform, SEO-clean, and easy to handle with dynamic [lang]/ routes + getStaticPaths. (If you'd rather have the default locale served at / without a prefix, set it to false and use file-based pages instead of [lang]/. The example uses the prefixed shape because it scales better.)
Download translations from Locize at build time
Add to package.json:
{
"scripts": {
"downloadLocales": "locize download --project-id=<your-id> --ver=latest --cdn-type=standard --clean=true --path=./src/i18n/locales",
"syncLocales": "locize sync --project-id=<your-id> --ver=latest --cdn-type=standard --api-key=<your-write-key> --path=./src/i18n/locales --dry=true"
}
}Run npm run downloadLocales before npm run build (manually, in CI, or as a prebuild hook) so the bundled JSON is always fresh.
Standard vs Pro CDN. Locize ships two CDN infrastructures (full comparison at CDN types: Standard vs. Pro): Standard at
api.lite.locize.appis BunnyCDN-backed, free for generous monthly download volumes, public-only (default for new projects); Pro atapi.locize.appis CloudFront-backed, paid, supports private downloads + custom cache control. Match--cdn-typeon the cli flag to whatever your project is on.
i18next in src/i18n/index.ts
Locize emits one JSON per namespace per language, which is exactly how i18next organises its resources. One module loads every downloaded file and initialises i18next once:
import i18next, { type Namespace } from 'i18next'
// Every file locize-cli downloads: ./locales/{lng}/{ns}.json
const files = import.meta.glob<{ default: Record<string, string> }>('./locales/*/*.json', { eager: true })
const resources: Record<string, Record<string, Record<string, string>>> = {}
for (const [path, mod] of Object.entries(files)) {
const [, lng, ns] = path.match(/\.\/locales\/([^/]+)\/([^/]+)\.json$/)!
resources[lng] ??= {}
resources[lng][ns] = mod.default
}
export const languages = { en: 'English', de: 'Deutsch' } as const
export type Lang = keyof typeof languages
export const defaultLang: Lang = 'en'
// An instance of its own, apart from any island that uses i18next in the browser.
const i18n = i18next.createInstance()
i18n.init({
resources, // bundled, so init finishes right away
fallbackLng: defaultLang,
defaultNS: 'common',
interpolation: { escapeValue: false } // Astro escapes what {t(...)} renders
})
// A t() bound to one language (and optionally one namespace).
export const getT = <N extends Namespace>(lang: Lang, ns?: N) => i18n.getFixedT(lang, ns)
// The same page in another language: swap the /{lang}/ prefix.
// "/en/second/" → "/de/second/"
export function pathForLang (pathname: string, target: Lang): string {
const parts = pathname.split('/')
parts[1] = target
return parts.join('/')
}What this gives you:
- No import list to maintain.
import.meta.globpicks up every filelocize-clidownloads, so a new namespace or language from Locize needs no code change (only the language inlocalesinastro.config.mjsand a label inlanguages). - Namespaces as files.
getT(lang, 'index')returns at()for one language and namespace; keys from another namespace take a prefix:t('common:headTitle'). - Fallbacks. A key missing in German falls back to English (
fallbackLng). - Interpolation and plurals in the format Locize stores by default (i18next JSON v4):
{{name}}for values,_one/_othersuffixes pluscountfor plurals, with each language's plural rules:
{
"title": "Hello, {{name}}!",
"loaves_one": "{{count}} loaf left",
"loaves_other": "{{count}} loaves left"
}Typed keys work too: i18next's TypeScript support reads the key names from your default-language JSON.
Using t() in pages
Dynamic [lang]/ routes + getStaticPaths mean Astro pre-renders one HTML file per locale at build time:
---
// src/pages/[lang]/index.astro (excerpt)
import Layout from '../../layouts/Layout.astro'
import { getT, languages, type Lang } from '../../i18n'
import { getRelativeLocaleUrl } from 'astro:i18n'
export function getStaticPaths () {
return Object.keys(languages).map(lang => ({ params: { lang } }))
}
const { lang } = Astro.params as { lang: Lang }
const t = getT(lang, 'index')
---
<Layout lang={lang} title={t('common:headTitle')}>
<h1>{t('title', { name: 'Astro' })}</h1>
<p>{t('subtitle')}</p>
<p>{t('loaves', { count: 1 })} · {t('loaves', { count: 3 })}</p>
<p>
<a href={getRelativeLocaleUrl(lang, 'second/')}>
{t('goto.second')}
</a>
</p>
</Layout>The getStaticPaths function maps each locale to a static path; lang arrives as a route param. Pure build-time work: no server-side runtime, no hydration. The build writes /en/index.html with "Hello, Astro!" and "1 loaf left · 3 loaves left", and /de/index.html with "Hallo, Astro!" and "1 Brot übrig · 3 Brote übrig", and no JavaScript file.
The language picker and hreflang links
Astro's docs i18n recipe shows a simple picker that swaps the locale prefix on the current URL; pathForLang from src/i18n/index.ts does the swap:
---
// src/components/LanguagePicker.astro (excerpt)
import { languages, pathForLang, type Lang } from '../i18n'
interface Props {
currentLang: Lang
}
const { currentLang } = Astro.props
---
<nav>
<ul>
{Object.entries(languages).map(([lang, label]) => (
<li>
{lang === currentLang ? (
<strong>{label}</strong>
) : (
<a href={pathForLang(Astro.url.pathname, lang as Lang)}>{label}</a>
)}
</li>
))}
</ul>
</nav>Drop it into src/layouts/Layout.astro and it's available on every page. The same layout writes the hreflang links, so search engines know which page is which language; Astro's routing does not add them:
---
// src/layouts/Layout.astro (head excerpt)
import { languages, defaultLang, pathForLang, type Lang } from '../i18n'
const { lang, title } = Astro.props
---
<html lang={lang}>
<head>
<title>{title}</title>
{Object.keys(languages).map(l => (
<link rel="alternate" hreflang={l} href={new URL(pathForLang(Astro.url.pathname, l as Lang), Astro.site)} />
))}
<link rel="alternate" hreflang="x-default" href={new URL(pathForLang(Astro.url.pathname, defaultLang), Astro.site)} />
</head>Three ways to land new keys in Locize
Astro is static-by-default: pages are pre-rendered, so a runtime saveMissing push from production users isn't possible without an SSR adapter, and Astro discourages writes from the static layer anyway. There are three workable paths instead:
npm run syncLocales(wired inpackage.json, drop the--dry=trueflag to actually push).locize-clireads your localsrc/i18n/locales/{lng}/{ns}.jsonand uploads any keys not yet in Locize. Manual or CI-triggered, no write-key in the browser.- Static extraction via
i18next-cli: it findst('…')calls in.js,.ts,.jsxand.tsxfiles out of the box and writes new keys into the local JSON, then sync up as above..astrofiles need a plugin through its plugin hooks; without one, i18next-cli does not read them. - The Locize web app: add keys directly in the editor and pull them down with
downloadLocalesbefore the next build.
Pick whichever fits your workflow. None of them require shipping a write API key in your build artifact.
What this shape intentionally doesn't include
Three things you might expect from the Nuxt or React Router v7 walkthroughs are deliberately absent here:
- No runtime
saveMissing. See above: Astro static builds can't push, and an SSR Astro app would do this from inside an island, not from the static layer. - No in-context editor on static pages. The
locizeeditor needs a DOM that re-renders when the editor updates a string. Astro's static output doesn't have that hook. - No live CDN fetch. Translations are bundled at build time. To serve a fresh translation, run
npm run downloadLocalesand redeploy. This matches Astro's static-first model and keeps the build artifact self-contained.
All three of these do work inside framework islands. Mount a React, Vue, Svelte, Solid, or Preact island via the matching @astrojs/<framework> integration, and inside that island use i18next-locize-backend + the locize package directly. The Astro static layer handles the routing + the page chrome; the islands handle the parts that need a runtime. Pages and islands use the same library and the same JSON format.
When to add a framework island
The static-only integration covers most content sites: blogs, marketing pages, docs, landing pages. Add a framework island when you need:
- Live translation updates without a redeploy. Use
i18next-locize-backendinside the island to fetch translations from the Locize CDN on each visit (or per-route, if you cache). - In-context editing for translators. The
locizepackage's?incontext=trueoverlay needs a runtime that re-renders on string changes, only available inside a hydrated island. - Runtime
saveMissing. Same constraint: a hydrated island can push new keys; static HTML can't.
The pattern looks like this (for a React island):
---
// src/pages/[lang]/interactive.astro
import Layout from '../../layouts/Layout.astro'
import I18nIsland from '../../components/I18nIsland.tsx'
import { languages, type Lang } from '../../i18n'
export function getStaticPaths () {
return Object.keys(languages).map(lang => ({ params: { lang } }))
}
const { lang } = Astro.params as { lang: Lang }
---
<Layout lang={lang} title="Interactive">
<I18nIsland client:load lang={lang} />
</Layout>// src/components/I18nIsland.tsx
import i18next from 'i18next'
import Backend from 'i18next-locize-backend'
import { initReactI18next, useTranslation } from 'react-i18next'
i18next
.use(Backend)
.use(initReactI18next)
.init({
fallbackLng: 'en',
saveMissing: import.meta.env.DEV,
backend: {
projectId: import.meta.env.PUBLIC_LOCIZE_PROJECT_ID,
apiKey: import.meta.env.DEV ? import.meta.env.PUBLIC_LOCIZE_API_KEY : undefined, // dev only; the browser sees only PUBLIC_ variables
version: 'latest'
}
})
export default function I18nIsland ({ lang }: { lang: string }) {
const { t, i18n } = useTranslation()
if (i18n.language !== lang) i18n.changeLanguage(lang)
return <h2>{t('island.heading')}</h2>
}client:load tells Astro to hydrate this component immediately on page load; you can use client:visible to defer hydration until the island enters the viewport. The exact configuration of i18next-locize-backend is documented in the React Router v7 walkthrough; the same backend wiring works in any React/Vue/Svelte/Solid context, including inside an Astro island.
🎉 Congratulations
A working Astro 7 + i18next + Locize setup gives you:
- Static-first i18n with no flash of untranslated content and no translation JavaScript in the browser (everything is pre-rendered per locale)
- SEO-clean URL prefixing via Astro's built-in i18n routing, with hreflang links from the layout
- A full
t()from i18next: plurals, interpolation, fallbacks, namespaces - Build-time translation sync via
locize-cli: serverless-friendly, no per-request CDN hop - An escape hatch to dynamic islands, with the same library and files, when you need runtime updates or in-context editing
🧑💻 The complete code: github.com/locize/locize-astro-example.
The founders of Locize are also the creators of i18next. By using Locize you directly support the future of i18next.
See also
- How to internationalize a Nuxt 4 app with @nuxtjs/i18n and Locize: Vue-side counterpart with richer integration (vue-i18n, in-context editor, runtime saveMissing)
- How to internationalize a React Router v7 app with remix-i18next: React-side counterpart with live CDN fetch via
i18next-locize-backend - Astro's built-in i18n routing: the routing primitive this walkthrough builds on
- Astro i18n recipe: the build-it-yourself pattern that i18next replaces here
- i18next documentation:
t(), plurals, interpolation, TypeScript locize-cli: the build-time sync tool
Tired of managing translations by hand?
Locize is the translation management backend by the i18next team: CDN delivery, AI translation, in-context editing, no redeploys.
Start your free 14-day trial
