Many bilingual small business sites keep both languages in one HTML file and hide one with CSS or a JavaScript toggle. A visitor sees one language. Googlebot sees both on the same URL. Google's documentation on multilingual sites is direct about this: Google "recommends using different URLs for each language version of a page rather than using cookies or browser settings to adjust the content language on the page".
The fix is one language per URL, English at / and Spanish at /es/, with hreflang tags linking each pair. Everything below was built and checked on 12 November 2026 with Astro 7.4.11 and @astrojs/sitemap 3.7.4, the current npm releases on that date. Every rule is quoted from Google Search Central or the Astro documentation, and the build output shown in step 7 is copied from a real npm run build.
hreflang is now mainstream. The HTTP Archive's 2025 Web Almanac SEO chapter, published 15 January 2026, found it on about 20% of pages, roughly double the 9 to 10% of 2024. On home pages the most common values are en (7.4% of mobile home pages), x-default (6.9%) and es (3.0%). The same chapter reports that hreflang pointing at http:// URLs is down to 0.1% of mobile pages, so an https:// URL in every tag is the baseline, not an extra.
1. Check whether you have the problem
Open View Source on an English page and search for a Spanish word from your copy. Or do it from the terminal:
curl -s https://example.com/contact/ | grep -c "Contáctenos"
Anything above 0 means the Spanish text ships inside the English page. The other symptom is a language switcher that only changes a cookie or a localStorage value while the URL stays the same. Either one means you need the refactor below.
2. Turn on Astro's i18n routing
In astro.config.mjs:
import { defineConfig } from "astro/config";
import sitemap from "@astrojs/sitemap";
export default defineConfig({
site: "https://example.com",
trailingSlash: "always",
i18n: {
locales: ["en", "es"],
defaultLocale: "en",
routing: { prefixDefaultLocale: false },
},
integrations: [
sitemap({
i18n: {
defaultLocale: "en",
locales: { en: "en", es: "es" },
},
}),
],
});
prefixDefaultLocale: false is the default. Writing it out documents that English stays at the root, so existing URLs keep working with no redirects. site is required because the sitemap integration and getAbsoluteLocaleUrl() need it to build full URLs. The Astro i18n reference says that if site isn't configured "the function returns a relative URL", and Google requires absolute ones.
English pages stay in src/pages/. Spanish pages go in src/pages/es/. The Astro i18n guide states two rules for the folders: "Your folder names must match the items in locales exactly", and you include a folder for the default locale "only if you configure prefixDefaultLocale: true".
src/pages/
index.astro
contact.astro
services/water-heaters.astro
es/
index.astro
contact.astro
servicios/calentadores.astro
Move copy into src/i18n/en.ts and src/i18n/es.ts and pick the right file with Astro.currentLocale. The Astro API reference defines it as "the locale computed from the current URL", falling back to i18n.defaultLocale when the URL has no locale prefix. It works on static pages, unlike Astro.preferredLocale, which "is only available for routes rendered on demand and cannot be used on prerendered, static pages".
3. Pick the right language code
For a US business with one Spanish version, use plain es.
-
esmatches every Spanish-speaking searcher, whatever country their browser reports. -
es-UStargets Spanish speakers in the United States only. That's worth it only if you also publish a separatees-MXores-ESversion. -
es-ESmeans Spain. The Astro sitemap documentation useses: 'es-ES'in its example config, so it gets copied onto American sites by accident.
Google's hreflang documentation, last updated 21 September 2026, sets the format: a language code in ISO 639-1, optionally followed by a region code in ISO 3166-1 Alpha 2. It adds that "other codes that aren't listed in those standards, such as es-419, aren't supported". The value is case-insensitive, but uppercase regions like en-US follow the ISO convention. A region on its own, such as US, is invalid: "Specifying the region alone is not valid."
4. Add a reusable hreflang component
Google's rules, from the guidelines section of the same page: "Each language version must list itself as well as all other language versions", alternate URLs "must be fully-qualified, including the transport method (http/https)", and "if two pages don't both point to each other, the tags will be ignored". Google's canonicalization documentation adds that when you use hreflang you should "specify a canonical page in the same language". This component does all four things and adds x-default:
---
// src/components/HreflangLinks.astro
import { getAbsoluteLocaleUrl } from "astro:i18n";
interface Props {
// Only needed when slugs differ by language, e.g.
// { en: "/services/water-heaters/", es: "/es/servicios/calentadores/" }
// Leave a locale out when that page has no translation.
paths?: Record<string, string>;
}
// Locale folder -> hreflang value
const HREFLANG: Record<string, string> = { en: "en", es: "es" };
const DEFAULT_LOCALE = "en";
const { paths } = Astro.props;
const current = Astro.currentLocale ?? DEFAULT_LOCALE;
// "/es/contact/" -> "contact", "/contact/" -> "contact", "/es/" -> ""
const bare = Astro.url.pathname
.replace(/^\/es(?=\/|$)/, "")
.replace(/^\/|\/$/g, "");
const alternates = paths
? Object.entries(paths).map(([locale, path]) => ({
locale,
href: new URL(path, Astro.site).href,
}))
: Object.keys(HREFLANG).map((locale) => ({
locale,
href: getAbsoluteLocaleUrl(locale, bare),
}));
const self = alternates.find((a) => a.locale === current);
const fallback = alternates.find((a) => a.locale === DEFAULT_LOCALE);
---
{self && <link rel="canonical" href={self.href} />}
{alternates.length > 1 && alternates.map((a) => (
<link rel="alternate" hreflang={HREFLANG[a.locale]} href={a.href} />
))}
{alternates.length > 1 && fallback && (
<link rel="alternate" hreflang="x-default" href={fallback.href} />
)}
getAbsoluteLocaleUrl() respects the trailingSlash: "always" setting, so getAbsoluteLocaleUrl("es", "contact") returns https://example.com/es/contact/ and getAbsoluteLocaleUrl("en", "") returns https://example.com/. That's why the component strips the slashes from bare instead of keeping them.
Use it in the base layout and set lang on <html> from the same value:
---
// src/layouts/Base.astro
import HreflangLinks from "../components/HreflangLinks.astro";
const { title, description, paths } = Astro.props;
const lang = Astro.currentLocale ?? "en";
---
<html lang={lang}>
<head>
<meta charset="utf-8" />
<title>{title}</title>
<meta name="description" content={description} />
<HreflangLinks paths={paths} />
</head>
<body><slot /></body>
</html>
Google states it "doesn't use hreflang or the HTML lang attribute to detect the language of a page". Set lang anyway. MDN's documentation for the attribute says its purpose "is primarily to allow assistive technologies such as screen readers to invoke the correct pronunciation".
For an English-only page, pass paths={{ en: "/careers/" }}. The component then prints only the canonical, so you never point Google at a Spanish URL that returns 404.
On x-default: Google describes it as "the fallback page for users whose language settings don't match any of your site's localized versions", adds that "you can use the x-default value for any page", and notes it was designed for language selector pages. For a two-language site with no selector page, pointing x-default at the English version is the common choice. The Astro docs site does exactly this, as step 7 shows.
5. Decide on slugs: translate or mirror
Google's multilingual documentation says "it's fine to use localized words in the URL" as long as you use UTF-8 and escape the URLs when linking. So you have two options:
- Mirror the slugs (
/es/contact/). Nopathsprop needed, and the sitemap integration pairs the pages for you. - Translate them (
/es/servicios/calentadores/). Reads naturally to Spanish speakers, but you passpathson both pages of the pair.
Translate the service pages people find in search. Mirror contact, privacy and the like.
Now the catch, visible in the integration's source file generate-sitemap.ts. The code comment says it will "find all URLs with the same path (without the locale part), e.g. /en/foo and /es/foo", and when it finds only the page itself it returns no links at all. Translated slugs never match, so those URLs get no xhtml:link alternates in the sitemap. The source also pushes only the configured locales, so the sitemap never contains an x-default entry. This is what dist/sitemap-0.xml contained after the test build for this article (line breaks added):
<url><loc>https://example.com/contact/</loc>
<xhtml:link rel="alternate" hreflang="en" href="https://example.com/contact/"/>
<xhtml:link rel="alternate" hreflang="es" href="https://example.com/es/contact/"/></url>
<url><loc>https://example.com/es/servicios/calentadores/</loc></url>
<url><loc>https://example.com/services/water-heaters/</loc></url>
The mirrored contact pair gets en and es alternates and no x-default. The translated water heater pair gets nothing. Google reads hreflang from the <head> as well as from sitemaps, and a page's head tags are the complete set here, so the sitemap gap doesn't break anything. Just don't treat the sitemap as proof that the pairing is right.
6. Make the language switcher a real link
The switcher is an <a href> to the same page in the other language, not a button that sets a cookie and not a link to /es/ from every page. Build the href from the same paths data, or from getRelativeLocaleUrl("es", bare) for mirrored slugs, so it can't disagree with the hreflang tags.
Don't redirect by IP address or Accept-Language. Google's multilingual documentation says to "avoid automatically redirecting users from one language version of a site to a different language version", because such redirects "could prevent users (and search engines) from viewing all the versions of your site". It also explains why the crawler would miss /es/ entirely: "the Googlebot crawler usually originates from the USA" and "sends HTTP requests without setting Accept-Language in the request header". Google's suggestion is to add hyperlinks to the other language version so users can choose. A dismissible banner linking to the Spanish page does that. On a static Astro site you couldn't read Accept-Language at build time anyway, which is why Astro.preferredLocale only exists on routes rendered on demand.
7. Verify the build
npm run build
grep -o '<html[^>]*>\|<link rel="\(canonical\|alternate\)"[^>]*>' dist/es/contact/index.html
grep -c "Contáctenos" dist/contact/index.html # must print 0
This is what the first grep printed for the Spanish contact page of a seven-page test project built with the config, component and layout above on Astro 7.4.11:
<html lang="es">
<link rel="canonical" href="https://example.com/es/contact/">
<link rel="alternate" hreflang="en" href="https://example.com/contact/">
<link rel="alternate" hreflang="es" href="https://example.com/es/contact/">
<link rel="alternate" hreflang="x-default" href="https://example.com/contact/">
The same grep on dist/contact/index.html printed <html lang="en">, a canonical of https://example.com/contact/, and the same three alternate lines. That identical set on both sides is the bidirectional rule in practice. The translated pair behaved the same way: dist/es/servicios/calentadores/index.html carried a Spanish canonical plus en, es and x-default links built from the paths prop, and dist/careers/index.html carried one canonical and no alternate tags at all. The second grep printed 0.
The Astro documentation site is a live example of the same pattern at a larger scale. These are real lines from curl -s https://docs.astro.build/es/guides/internationalization/ on 12 November 2026, with the twelve other languages it lists cut out:
<html lang="es" dir="ltr" ...>
<link rel="canonical" href="https://docs.astro.build/es/guides/internationalization/"/>
<link rel="alternate" hreflang="en" href="https://docs.astro.build/en/guides/internationalization/"/>
<link rel="alternate" hreflang="es" href="https://docs.astro.build/es/guides/internationalization/"/>
<link rel="alternate" hreflang="x-default" href="https://docs.astro.build/en/guides/internationalization/"/>
The Spanish page carries a Spanish canonical, lists itself and English, and x-default points at English. Its sitemap-0.xml has xhtml:link alternates per URL and no x-default, the same behaviour the integration source predicts.
After deploy, submit sitemap-index.xml in Search Console. Then wait. The Page indexing report documentation states that "alternate language pages are not detected by Search Console", so there is no report that confirms your pairs. The check that works is URL Inspection on a Spanish page a few weeks after launch: the "Google-selected canonical" field should show the Spanish URL. The URL Inspection documentation says you can determine the canonical "only in the indexed data; the live test cannot predict" it, so the live test won't answer this question on day one.
Two mistakes that silently undo the work
- Canonicals that cross languages. Pointing
/es/contact/at/contact/tells Google the Spanish page is a duplicate of the English one, and Google's canonicalization documentation says to pick "a canonical page in the same language". The component above can't produce a cross-language canonical, which is the point of generating both tags from one source. - An English template string leaking into Spanish pages, usually a shared header, footer or form label. Google's multilingual guidance says to use "a single language for content and navigation on each page" and to avoid "side-by-side translations". The
grep -ccheck in step 7 catches body copy. Add one grep per shared component string.
Illustrative example
A heating and air conditioning company in Texas has twelve English pages. It wants Spanish for the six service pages and the contact page, and nothing else. The plan that follows from the rules above:
| Page | English URL | Spanish URL |
paths prop |
|---|---|---|---|
| Home | / |
/es/ |
none, mirrored |
| Contact | /contact/ |
/es/contact/ |
none, mirrored |
| AC repair | /services/ac-repair/ |
/es/servicios/reparacion-de-aire-acondicionado/ |
both pages |
| Careers | /careers/ |
no translation | { en: "/careers/" } |
Two mirrored pairs need no props and get sitemap alternates for free. Six translated service pairs pass paths on both sides and rely on head tags only. Careers prints a canonical and nothing else. Every hreflang value is es or en, and every x-default points at the English page in the pair. The whole set is checked with the three grep commands before the Spanish copy for the remaining pages is even written.
The prompt
Paste this into your coding tool from the repository root and fill in the brackets:
My Astro site needs separate English and Spanish pages with correct hreflang. [Describe the current setup: both languages in one HTML file hidden with CSS / no Spanish yet.]
Site URL: [https://example.com] | Default: English at / | Spanish at /es/ | Astro version: [version]
Pages to translate: [list of paths]
Slug rule: [translate slugs for these pages: ... / mirror all slugs]
1. In astro.config.mjs set site, i18n.locales ["en","es"], defaultLocale "en", routing.prefixDefaultLocale false. Add @astrojs/sitemap with i18n locales { en: "en", es: "es" }.
2. Put Spanish pages in src/pages/es/. Move all copy into src/i18n/en.ts and es.ts. One language per rendered page. Delete any CSS or JavaScript language toggle and any stored language preference.
3. Create src/components/HreflangLinks.astro: self-referencing canonical, absolute https hreflang links for every language version including itself, and x-default pointing to English. Accept an optional paths prop for translated slugs. Emit no hreflang on pages with no translation.
4. Set <html lang> from Astro.currentLocale. Translate title, meta description and Open Graph tags.
5. Language switcher: a plain <a> to the same page in the other language, built from the same paths data.
6. Never point a canonical across languages. No redirects based on IP or Accept-Language.
7. Use hreflang "es", not "es-ES" or "es-US".
Before finishing: run the build, grep dist/ to show the canonical and hreflang tags on [two English pages] and their Spanish pairs, confirm the alternate sets are identical on both sides, and confirm no English body text appears in dist/es/.
Check the output by comparing the <link> tags of two paired pages in dist/ line by line. If the sets differ, Google ignores the pair.
Where to start
Do the homepage and your most-searched service page in both languages and run the three grep commands before translating anything else. Once those two pairs print identical alternate sets, the rest is copy work.
This article was written with AI assistance and checked by a person.
If that's too much work, contact us and we'll make you a free website.
Top comments (0)