LanguagesLanguage switcher and hreflang

Language switcher and hreflang

Every page and entry knows its own address in every language. A language switcher links from that map, and the site's hreflang tags come from the same one.

View as Markdown

The language map

A page type's view gets page.locales, and an entry page gets locales: one key per supported language. The value is the page's slug, path and url in that language, or null where the page does not exist or is not published there. In the editor's canvas an unpublished translation still counts; on the public site it never links.

A switcher links to the same page where it exists, and to that language's home otherwise. The blank starter does it in one component:

src/components/LocaleNav.astro
---
import { href } from "smoodly/astro/runtime";
// …
const codes = Object.keys(locales);
---
{codes.length > 1 && (
  <nav class="container locales" aria-label="Language">
    {codes.map((code) => <a href={href(locales[code]?.path ?? "/", code)} aria-current={code === locale ? "page" : undefined}>{code}</a>)}
  </nav>
)}

href from smoodly/astro/runtime adds the language prefix the site uses. With one language the map has one key and the component renders nothing, which is why the single-language scaffold shares the file.

Why the page decides it

The links must land on the same page in the other language, so they come from the page on screen.

Every page view passes its own locales map to the layout, and the layout renders the header with the links. Astro renders the page before its layout, so the layout knows which page is on screen. Header and footer has the file.

hreflang

Head from smoodly/astro/components writes one hreflang link per language where the page is published, from the same map the switcher reads. A single-language site gets none, only the page's canonical link. The links are absolute on site in astro.config.ts, which the starter reads from SITE_URL: set it to the site's real address, as SEO explains.

src/layouts/Layout.astro
    <Head of={head} fallback="Lorem Co." />

The visitor picks a language through the switcher; nothing redirects by browser language.

Next, Frameworks.

Edit this page on GitHubLast updated 6 Oct 2026