Language Switcher
To create a language switcher in Astro that maintains the current page, use the normalize prop of the Link component.
Implementation Example
---
import Link from '@i18n-tiny/astro/router/Link.astro'
import { locales } from '../i18n'
const { locale: currentLocale } = Astro.params
const pathname = Astro.url.pathname
---
<div class="flex gap-4">
{locales.map((loc) => (
<Link
href={pathname}
locale={loc}
normalize
class={loc === currentLocale ? 'font-bold' : ''}
>
{loc.toUpperCase()}
</Link>
))}
</div>
How it works
Astro.url.pathnamereturns the current path (e.g.,/ja/about).Linkreceives/ja/aboutashrefandenaslocale.- Because
normalizeis set totrue, theLinkcomponent removes the existing/japrefix before applying the new/enprefix, resulting in/en/about.