Skip to content

Blog

Astro language switcher with i18n routing and hreflang

Frank Spin8 min read

A language switcher in Astro takes about 30 lines: Astro's built-in i18n routing tells you the current locale, getRelativeLocaleUrl() builds the same page's URL in every other language, and one check keeps you from linking to translations that don't exist. Below is the full component, the hreflang tags that go with it, and what to do with pages that only exist in one language.

We built and ran every snippet here in a fresh project on Astro 7.3.5 with astro build, and the HTML output shown is copied from that build. Nothing in it needs an integration or a client-side script, so the switcher ships zero JavaScript.

1. Turn on i18n routing#

Astro has had routing for languages built in since version 4. You list your locales, pick a default, and decide whether the default language gets a prefix in the URL:

// astro.config.mjs
import { defineConfig } from 'astro/config';

export default defineConfig({
  site: 'https://example.com',
  trailingSlash: 'always',
  i18n: {
    locales: ['en', 'nl', 'de'],
    defaultLocale: 'en',
    routing: { prefixDefaultLocale: false },
  },
});

With prefixDefaultLocale: false, English lives at /about/ and the translations at /nl/about/ and /de/about/. Your files mirror that: src/pages/about.astro, src/pages/nl/about.astro, src/pages/de/about.astro. Set site too, because the hreflang tags further down need absolute URLs.

Two things this config gives you on every page: Astro.currentLocale, the locale of the page being rendered (nl on /nl/about/), and the helpers in the astro:i18n module, which build URLs that respect your trailingSlash and prefix settings.

2. The language switcher component#

The switcher has one job: for the page you're on, link to the same page in each other language. That means taking the current path, removing the locale prefix, and asking Astro for that path in every locale.

Put the shared logic in one file, because the hreflang tags need it too:

// src/lib/i18n.ts
import { getRelativeLocaleUrl } from 'astro:i18n';

export const locales = { en: 'English', nl: 'Nederlands', de: 'Deutsch' } as const;
export type Locale = keyof typeof locales;
export const defaultLocale: Locale = 'en';

// Every page file, turned into the URL it builds: src/pages/nl/about.astro -> /nl/about/
const urls = new Set(
  Object.keys(import.meta.glob('/src/pages/**/*.{astro,md,mdx}')).map((file) =>
    file.replace(/^\/src\/pages/, '').replace(/(\/index)?\.(astro|mdx?)$/, '/').replace(/\/+$/, '/') || '/',
  ),
);

/** The path without its locale prefix: /nl/about/ becomes /about/. */
export const stripLocale = (pathname: string, current: string) =>
  pathname.replace(new RegExp(`^/${current}(?=/|$)`), '') || '/';

/** The same page in another language, or null when that translation doesn't exist. */
export function translatedUrl(locale: Locale, path: string): string | null {
  const url = getRelativeLocaleUrl(locale, path);
  return urls.has(url) ? url : null;
}

The (?=/|$) in stripLocale is there for the default locale. English pages have no prefix, so on /enterprise/ the current locale is en and a plain ^/en would strip the path to terprise/. The lookahead only removes the locale when it's a whole path segment.

The component itself:

---
// src/components/LanguageSwitcher.astro
import { locales, defaultLocale, stripLocale, translatedUrl, type Locale } from '../lib/i18n';

const current = (Astro.currentLocale ?? defaultLocale) as Locale;
const path = stripLocale(Astro.url.pathname, current);
const links = (Object.keys(locales) as Locale[]).map((code) => ({
  code,
  name: locales[code],
  // No translation of this page: send the reader to that language's home page instead of a 404.
  href: translatedUrl(code, path) ?? translatedUrl(code, '/'),
}));
---
<nav aria-label="Language">
  <ul class="flex gap-4 text-sm">
    {links.map(({ code, name, href }) => (
      <li>
        <a
          href={href}
          hreflang={code}
          lang={code}
          aria-current={code === current ? 'page' : undefined}
          class={code === current ? 'font-semibold' : 'text-muted-foreground hover:text-foreground'}
        >{name}</a>
      </li>
    ))}
  </ul>
</nav>

On /nl/about/ the build renders:

<a href="/about/" hreflang="en" lang="en" class="text-muted-foreground hover:text-foreground">English</a>
<a href="/nl/about/" hreflang="nl" lang="nl" aria-current="page" class="font-semibold">Nederlands</a>
<a href="/de/about/" hreflang="de" lang="de" class="text-muted-foreground hover:text-foreground">Deutsch</a>

A few choices in there are deliberate:

  • Each language is written in its own language ("Deutsch", not "German"). A German reader stuck on the Dutch site can't read the word "Duits".
  • lang on each link makes screen readers pronounce the name correctly; hreflang tells browsers and crawlers which language the target is in.
  • aria-current="page" marks the language you're in, so it's announced and you can style it without a second class list.
  • No flags. A flag is a country, not a language: Spanish isn't only Spain, English isn't only the UK.

The classes are Tailwind with shadcn/ui color tokens (text-muted-foreground, hover:text-foreground), so the switcher follows your theme and dark mode. Use any classes you like.

3. Pages that exist in one language only#

This is where most switchers break. Say your blog post /news/ exists only in English. A switcher that only swaps the prefix links to /nl/news/ anyway: a 404 for every Dutch reader who clicks it.

The import.meta.glob set in i18n.ts knows which pages were built. When a translation is missing, translatedUrl() returns null and the switcher falls back to that language's home page. On /news/ our build renders:

<a href="/news/" hreflang="en" lang="en" aria-current="page" class="font-semibold">English</a>
<a href="/nl/" hreflang="nl" lang="nl" class="text-muted-foreground hover:text-foreground">Nederlands</a>
<a href="/de/" hreflang="de" lang="de" class="text-muted-foreground hover:text-foreground">Deutsch</a>

If you'd rather hide the link than redirect to the home page, filter out the null entries instead.

Astro also has a built-in alternative: i18n.fallback. With fallback: { nl: 'en', de: 'en' } and routing.fallbackType: 'rewrite', Astro serves the English content at /nl/news/ instead of a 404. That keeps every link working, but it also publishes English text under a Dutch URL, which is duplicate content in search unless you set a canonical. For a marketing site we prefer the home-page fallback above.

Dynamic routes and content collections

The glob only sees files. A page built from src/pages/[lang]/blog/[slug].astro with getStaticPaths() doesn't show up as /nl/blog/hello/. For those, let the page pass its translations in: store a shared key in each entry's frontmatter (for example translationKey: hello), look up the entries with the same key in getStaticPaths(), and hand the switcher a ready-made { locale: url } map as a prop. That also handles translated slugs (/about/ and /nl/over-ons/), which a path swap can never get right.

4. hreflang tags for search engines#

The switcher is for people. Search engines want the same information in the <head>: one <link rel="alternate" hreflang> per language, on every version of the page, plus an x-default for readers whose language you don't have.

---
// src/layouts/Base.astro
import { locales, defaultLocale, stripLocale, translatedUrl, type Locale } from '../lib/i18n';
import LanguageSwitcher from '../components/LanguageSwitcher.astro';

const current = (Astro.currentLocale ?? defaultLocale) as Locale;
const path = stripLocale(Astro.url.pathname, current);
// hreflang only for translations that exist.
const alternates = (Object.keys(locales) as Locale[])
  .map((code) => ({ code, url: translatedUrl(code, path) }))
  .filter((a) => a.url);
const fallback = translatedUrl(defaultLocale, path);
---
<html lang={current}>
  <head>
    {alternates.length > 1 && alternates.map((a) => (
      <link rel="alternate" hreflang={a.code} href={new URL(a.url!, Astro.site)} />
    ))}
    {alternates.length > 1 && fallback && (
      <link rel="alternate" hreflang="x-default" href={new URL(fallback, Astro.site)} />
    )}
  </head>
  <body>
    <LanguageSwitcher />
    <slot />
  </body>
</html>

On /nl/about/ that gives four tags (en, nl, de and x-default, all absolute). On the English-only /news/ it gives none, which is correct: hreflang has to point at pages that exist and link back, or Google ignores the annotation.

Also set <html lang> from Astro.currentLocale, as above. It's the one tag screen readers, browser translation prompts and hyphenation all read.

With more than three or four languages, a row of links gets long. The no-JavaScript version is a <details> element around the same list:

<details class="relative">
  <summary class="cursor-pointer list-none text-sm">{locales[current]}</summary>
  <ul class="absolute right-0 mt-2 min-w-40 rounded-md border bg-popover p-1 shadow-md">
    {links.map(({ code, name, href }) => (
      <li>
        <a href={href} hreflang={code} lang={code} aria-current={code === current ? 'page' : undefined}
           class="block rounded-sm px-2 py-1.5 text-sm hover:bg-accent">{name}</a>
      </li>
    ))}
  </ul>
</details>

If your site already uses shadcn/ui in React islands, the DropdownMenu component gives you keyboard navigation and focus handling for free; render it with client:idle and pass links in as a prop. Our guide to shadcn/ui with Astro covers the setup.

FAQ#

Does Astro have a built-in language switcher?

No. Astro gives you the routing (i18n in the config), the current locale (Astro.currentLocale) and URL helpers (getRelativeLocaleUrl, getAbsoluteLocaleUrl), but the switcher component is yours to write. The one above is about 30 lines.

Should I use astro-i18next or another library?

For routing and a switcher, the built-in i18n is enough and has no dependencies. A library starts paying off when you need translated UI strings with plurals and interpolation; even then, many sites get by with a typed object per locale (const t = { en: {...}, nl: {...} }[current]).

Because it swaps the prefix without checking that the translation exists. Check against the built pages, as translatedUrl() does here, or use Astro's i18n.fallback to serve the default language at the missing URL.

Should the default language have a prefix like /en/?

Either works for search. Without a prefix (prefixDefaultLocale: false) your existing URLs stay the same when you add a second language, which is usually the deciding argument. With a prefix every language is treated alike, and the root / redirects to /en/.

Built on Tailwind CSS v4

1750 finished blocks on shadcn/ui, React and Astro

UI Pro, from €199

Build it with

Preview

Open the page
In UI Pro: get it, €199 once

With every block and theme. 400+ buyers since 2020. Plans

UI Pro

Build your next site from finished blocks

Every block, page template and website theme from €199, paid once, with every update and everything we add later. Not ready? The free blocks are open to everyone.

blocks
1750
page templates
55
website themes
33
The Case study page template from UI Pro, built from its blocks.

This page is built from UI Pro blocks: Zandloper (article-14), Rooilijn (call-to-action-07).