Astro
Use @better-translate/astro when your Astro app needs request-aware translations.
1. Install the packages
npm install @better-translate/core @better-translate/astro astro2. Create the translator
Create src/lib/i18n.ts:
ts
1import { configureTranslations } from "@better-translate/core";23const en = {4 home: {5 title: "Hello from Astro",6 },7} as const;89const es = {10 home: {11 title: "Hola desde Astro",12 },13} as const;1415export const translator = await configureTranslations({16 availableLocales: ["en", "es"] as const,17 defaultLocale: "en",18 fallbackLocale: "en",19 messages: { en, es },20});3. Expose the request config
Create src/lib/request.ts:
ts
1import { getRequestConfig } from "@better-translate/astro";23import { translator } from "./i18n";45export const requestConfig = getRequestConfig(async () => ({6 translator,7}));4. Set the request locale in middleware
Create src/middleware.ts:
ts
1import { createBetterTranslateMiddleware } from "@better-translate/astro/middleware";23import { requestConfig } from "./lib/request";45export const onRequest = createBetterTranslateMiddleware(requestConfig, {6 resolveLocale: ({ params }) => params?.lang,7});5. Read translations in a page
Create src/lib/server.ts:
ts
1import { createServerHelpers } from "@better-translate/astro";23import { requestConfig } from "./request";45export const { getLocale, getTranslations } =6 createServerHelpers(requestConfig);Create src/pages/[lang]/index.astro:
astro
1---2import { getLocale, getTranslations } from "../../lib/server";34const locale = await getLocale();5const t = await getTranslations();6---78<html lang={locale}>9 <body>10 <h1>{t("home.title")}</h1>11 </body>12</html>Optional next step
If your Astro docs or blog posts live in localized content collections, add Astro content helpers or the MDX adapter after this basic setup is working.
Generate locale files automatically
Instead of writing every translation by hand, use the CLI to extract strings and generate locale files: CLI guide