|
| 1 | +--- |
| 2 | +// src/components/LanguageDetector.astro |
| 3 | +// Client-side browser language detection with SEO-safe redirection. |
| 4 | +// Only performs automatic detection on the home page to avoid breaking |
| 5 | +// deep-linked / indexed pages. Manual preference (via header toggle) |
| 6 | +// is respected on ALL pages. |
| 7 | +import type { Lang } from '@/lib/i18n'; |
| 8 | +
|
| 9 | +interface Props { |
| 10 | + lang: Lang; |
| 11 | + alternateUrl?: string; |
| 12 | +} |
| 13 | +
|
| 14 | +const { lang, alternateUrl } = Astro.props; |
| 15 | +--- |
| 16 | + |
| 17 | +<script |
| 18 | + define:vars={{ pageLang: lang, alternateUrl: alternateUrl ?? null }} |
| 19 | +> |
| 20 | + (function detectLanguage() { |
| 21 | + const PREFERRED_LANG_KEY = 'preferred_lang'; |
| 22 | + const REDIRECTED_KEY = 'lang_redirected'; |
| 23 | + |
| 24 | + // Never redirect if we already redirected this session (prevents loops) |
| 25 | + if (sessionStorage.getItem(REDIRECTED_KEY)) return; |
| 26 | + |
| 27 | + const storedPref = localStorage.getItem(PREFERRED_LANG_KEY); |
| 28 | + const isHomePage = |
| 29 | + window.location.pathname === '/' || |
| 30 | + window.location.pathname === '/es/' || |
| 31 | + window.location.pathname === '/es'; |
| 32 | + |
| 33 | + /** @type {'en' | 'es' | null} */ |
| 34 | + let targetLang = null; |
| 35 | + |
| 36 | + if (storedPref === 'en' || storedPref === 'es') { |
| 37 | + // User has explicitly chosen a language before — respect it everywhere |
| 38 | + targetLang = storedPref; |
| 39 | + } else if (isHomePage) { |
| 40 | + // First visit, no preference saved — detect from browser, but ONLY on |
| 41 | + // the home page to preserve SEO for deep-linked pages. |
| 42 | + const browserLang = navigator.language || navigator.userLanguage || 'en'; |
| 43 | + targetLang = browserLang.startsWith('es') ? 'es' : 'en'; |
| 44 | + |
| 45 | + // Persist the detected preference so subsequent pages are consistent |
| 46 | + localStorage.setItem(PREFERRED_LANG_KEY, targetLang); |
| 47 | + } |
| 48 | + |
| 49 | + // If we have a target and it differs from the current page, redirect |
| 50 | + if (targetLang && targetLang !== pageLang && alternateUrl) { |
| 51 | + sessionStorage.setItem(REDIRECTED_KEY, '1'); |
| 52 | + window.location.replace(alternateUrl); |
| 53 | + } |
| 54 | + })(); |
| 55 | +</script> |
0 commit comments