A second language is one of the cheapest ways to reach more of the people a business already serves. For a great many businesses in the United States, a site in English and Spanish is simply the site their customers expect.
It is also where small sites go wrong in familiar ways. The Spanish page links back to the English home page. The menu is translated but the button under it is not. A search engine finds two pages and cannot tell they are the same page in two languages.
None of that needs a CMS or a translation service to fix. It needs a few files, kept in the right shape. This guide builds a two-language site in Astro 7 with nothing but the framework. The code below was built and run against Astro 7.4.5 before it went on this page, and the output shown is what the build produced.
Turn on Astro’s routing
Tell Astro which languages exist and which one is the default:
// astro.config.mjs
import { defineConfig } from 'astro/config';
import sitemap from '@astrojs/sitemap';
export default defineConfig({
site: 'https://example.com',
i18n: {
defaultLocale: 'en',
locales: ['en', 'es'],
// English at /about/, Spanish at /es/sobre-nosotros/
routing: { prefixDefaultLocale: false },
},
integrations: [sitemap({ i18n: { defaultLocale: 'en', locales: { en: 'en-US', es: 'es-ES' } } })],
});With prefixDefaultLocale: false, English keeps the short URLs and Spanish lives under /es/. That is the usual choice when one language came first: the addresses people already have keep working.
Keep every string in one typed file
Text that belongs to the interface, such as navigation, buttons and headings, goes in one file with a key for each string. English is the source, and Spanish is typed against it:
// src/i18n/strings.ts
export const en = {
'nav.home': 'Home',
'nav.about': 'About',
'home.title': 'Bread, baked at dawn',
'home.lead': 'A neighborhood bakery on Alder Street.',
'home.journal': 'From the journal',
'about.title': 'About the bakery',
'about.body': 'We have baked on this corner since {year}.',
} as const;
export type Key = keyof typeof en;
// Typed against English: leave a key out and the project stops compiling.
export const es: Record<Key, string> = {
'nav.home': 'Inicio',
'nav.about': 'Nosotros',
'home.title': 'Pan horneado al amanecer',
'home.lead': 'Una panadería de barrio en la calle Alder.',
'home.journal': 'Del diario',
'about.title': 'Sobre la panadería',
'about.body': 'Horneamos en esta esquina desde {year}.',
};
const strings = { en, es };
export type Locale = keyof typeof strings;
export const locales = Object.keys(strings) as Locale[];
export const defaultLocale: Locale = 'en';
/** `const t = useTranslations('es')`, then `t('about.body', { year: 1998 })` */
export function useTranslations(locale: Locale) {
return (key: Key, values: Record<string, string | number> = {}) =>
strings[locale][key].replace(/\{(\w+)\}/g, (match, name) => String(values[name] ?? match));
}That typing is the whole trick. The half-translated page, the most common fault on a bilingual site, becomes something the computer catches. Delete the Spanish for home.journal and astro check stops:
src/i18n/strings.ts:14:14 - error ts(2741): Property '"home.journal"' is missing in type ...Misspell a key in a page and it stops there too:
src/views/AboutView.astro:14:10 - error ts(2345): Argument of type '"about.heading"' is not assignable ...Run astro check before every deploy and a missing translation cannot reach the live site.
Give each page a slug in each language
A Spanish speaker searching for a bakery types “panadería”, not “bakery”, and a URL in their language reads as a page written for them. So each page gets a slug per language, in one map:
// src/i18n/routes.ts
import { defaultLocale, locales, type Locale } from './strings';
/** Every page and its slug in each language. An empty slug is the home page. */
export const routes = {
home: { en: '', es: '' },
about: { en: 'about', es: 'sobre-nosotros' },
} as const;
export type RouteId = keyof typeof routes;
/** The URL of a page in a language: "/about/" or "/es/sobre-nosotros/" */
export function localizeRoute(id: RouteId, locale: Locale) {
const prefix = locale === defaultLocale ? '' : `/${locale}`;
const slug = routes[id][locale];
return slug ? `${prefix}/${slug}/` : `${prefix}/`;
}
/** The same page in every language, for hreflang and the language switcher */
export function alternates(id: RouteId) {
return locales.map((locale) => ({ locale, href: localizeRoute(id, locale) }));
}From here on, no page writes a link by hand. Every link asks localizeRoute for the address, so a link on a Spanish page can only lead to another Spanish page.
One view, two thin pages
Astro routes from files, so the two addresses need two files. They should not need two copies of the page. Put the page in a view that takes the language, and make each route a wrapper around it:
---
// src/views/AboutView.astro
import Layout from '../layouts/Layout.astro';
import { useTranslations, type Locale } from '../i18n/strings';
interface Props {
locale: Locale;
}
const { locale } = Astro.props;
const t = useTranslations(locale);
---
<Layout route="about" locale={locale} title={t('about.title')} description={t('about.body', { year: 1998 })}>
<h1>{t('about.title')}</h1>
<p>{t('about.body', { year: 1998 })}</p>
</Layout>---
// src/pages/es/sobre-nosotros.astro
import AboutView from '../../views/AboutView.astro';
---
<AboutView locale="es" />src/pages/about.astro is the same three lines with locale="en". Change the design once and both languages change.
Say which language, and where the other one is
The layout does three jobs for search engines and one for visitors:
---
// src/layouts/Layout.astro
import { alternates, localizeRoute, type RouteId } from '../i18n/routes';
import { defaultLocale, useTranslations, type Locale } from '../i18n/strings';
interface Props {
route: RouteId;
locale: Locale;
title: string;
description: string;
}
const { route, locale, title, description } = Astro.props;
const t = useTranslations(locale);
const absolute = (path: string) => new URL(path, Astro.site).href;
/** A language's name in that language: "English", "español" */
const languageName = (code: string) => new Intl.DisplayNames([code], { type: 'language' }).of(code);
---
<html lang={locale}>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>{title}</title>
<meta name="description" content={description} />
<link rel="canonical" href={absolute(localizeRoute(route, locale))} />
{alternates(route).map((alt) => <link rel="alternate" hreflang={alt.locale} href={absolute(alt.href)} />)}
<link rel="alternate" hreflang="x-default" href={absolute(localizeRoute(route, defaultLocale))} />
</head>
<body>
<nav>
<a href={localizeRoute('home', locale)}>{t('nav.home')}</a>
<a href={localizeRoute('about', locale)}>{t('nav.about')}</a>
{
alternates(route)
.filter((alt) => alt.locale !== locale)
.map((alt) => (
<a href={alt.href} hreflang={alt.locale} lang={alt.locale}>
{languageName(alt.locale)}
</a>
))
}
</nav>
<slot />
</body>
</html>langon<html>tells browsers and screen readers which language to read the page in.- The canonical link names this page’s own address, in its own language.
- The
hreflanglinks pair the two pages, each pointing at both, withx-defaultfor visitors who match neither. - The switcher leads to the same page in the other language, not to the home page. It names the language in that language, with no flag: Spanish is an official language in some twenty countries, and a flag picks one of them.
Here is what the build wrote into the Spanish about page:
<html lang="es">
<link rel="canonical" href="https://example.com/es/sobre-nosotros/">
<link rel="alternate" hreflang="en" href="https://example.com/about/">
<link rel="alternate" hreflang="es" href="https://example.com/es/sobre-nosotros/">
<link rel="alternate" hreflang="x-default" href="https://example.com/about/">Its switcher reads “English” and leads to /about/. On the English page it reads “español” and leads to /es/sobre-nosotros/.
Translate the content, and the numbers
Longer writing, such as posts, menus and service descriptions, does not belong in the strings file. Keep it in a content collection, with a folder per language and the same file name for a translation:
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { glob } from 'astro/loaders';
import { z } from 'astro/zod';
const posts = defineCollection({
// src/content/posts/en/first-loaf.md and src/content/posts/es/first-loaf.md
loader: glob({ pattern: '**/*.md', base: './src/content/posts' }),
schema: z.object({
title: z.string(),
date: z.coerce.date(),
price: z.number().optional(),
}),
});
export const collections = { posts };A view then asks for the entries in its own language, and lets Intl write dates and money the way that language does:
---
// src/views/HomeView.astro
import { getCollection } from 'astro:content';
import Layout from '../layouts/Layout.astro';
import { useTranslations, type Locale } from '../i18n/strings';
interface Props {
locale: Locale;
}
const { locale } = Astro.props;
const t = useTranslations(locale);
// An entry's id starts with its folder: "es/first-loaf"
const posts = (await getCollection('posts')).filter((post) => post.id.startsWith(`${locale}/`));
const date = new Intl.DateTimeFormat(locale, { dateStyle: 'long', timeZone: 'UTC' });
const price = new Intl.NumberFormat(locale, { style: 'currency', currency: 'USD' });
---
<Layout route="home" locale={locale} title={t('home.title')} description={t('home.lead')}>
<h1>{t('home.title')}</h1>
<p>{t('home.lead')}</p>
<h2>{t('home.journal')}</h2>
<ul>
{
posts.map((post) => (
<li>
{post.data.title}, {date.format(post.data.date)}
{post.data.price && <>, {price.format(post.data.price)}</>}
</li>
))
}
</ul>
</Layout>The same entry, same date and same price came out of the build like this:
The first loaf of the year, January 2, 2026, $4.50
La primera hogaza del año, 2 de enero de 2026, 4,50 US$Nobody translated the date or moved the decimal comma. Hand-formatted dates are the detail that gives a translated site away.
Check the sitemap
The sitemap integration can list each page’s translations too, and with the i18n option above it did, for the home page:
<url>
<loc>https://example.com/es/</loc>
<xhtml:link rel="alternate" hreflang="en-US" href="https://example.com/"/>
<xhtml:link rel="alternate" hreflang="es-ES" href="https://example.com/es/"/>
</url>It did not for the about page. The integration pairs pages by their path, and /about/ and /es/sobre-nosotros/ no longer share one. This is the price of translated slugs: the sitemap lists both pages but does not say they are a pair. The hreflang links in each page’s head still do, and those are enough. It is worth knowing before you go looking for the missing lines.
Mistakes worth avoiding
- Redirecting by browser language. Sending a visitor to
/es/because their browser says Spanish breaks shared links and hides the English page from anyone who wanted it. Offer the switch; let them choose. - Translating the page and not the rest. Image alt text, the meta description, form error messages and the confirmation email are all part of the page. The typed strings file catches the ones that live in it. The others need a list.
- One 404 for both languages. A static build writes a single
404.html, in one language. If that matters to you, render the 404 on demand and pick the language from the first part of the path. In Velocity we read it from the URL for exactly this reason, becauseAstro.currentLocalereports the default language on a 404. - Publishing machine translation unread. It is a fine first draft. Have a native speaker read it before launch, and decide early whether you address the reader as tú or usted.
- Forgetting the other direction. Every Spanish page needs its way back to the same page in English. A switcher that only appears on the English side is half a switcher.
What Velocity does with all this
Velocity, our free Astro starter, ships this arrangement already built. You list your languages in one file and add a typed translations file for each. The /es/ pages, the language switcher, the hreflang links, a localized sitemap, search per language and share images per language come with it, and translated slugs are optional. npm create velocity-astro --i18n sets up English, Spanish and French from the first command.
Every Velocity Premium template goes one step further and ships fully written in both English and Spanish: all 9 of them, every page, with translated addresses. The Restaurant template’s menu is at /menu/ in English and /es/carta/ in Spanish. The Spanish in the templates is sample copy like the English, and each file says to have a native speaker review it before launch.
If you are building it by hand, everything above is yours to copy. Start with the typed strings file. It is the piece that keeps the two languages honest with each other.