Refactor About Me page for language detection and redirection

- Changed prerendering setting to true for improved performance.
- Implemented client-side language detection using cookies and browser settings.
- Added a redirect mechanism to the language-specific About Me page based on detected language.
- Included a fallback for users without JavaScript support.
This commit is contained in:
2025-07-02 22:38:54 +02:00
parent 28de900b95
commit 2cb5f4bf24

View File

@@ -1,33 +1,42 @@
---
export const prerender = false;
import { supportedLanguages } from '~/i18n/translations';
// Check for language preference in cookies (set by client-side JS)
const cookies = Astro.request.headers.get('cookie') || '';
const cookieLanguage = cookies
.split(';')
.map((cookie) => cookie.trim())
.find((cookie) => cookie.startsWith('preferredLanguage='))
?.split('=')[1];
// Get the user's preferred language from the browser if no cookie
const acceptLanguage = Astro.request.headers.get('accept-language') || '';
// Define the type for supported languages
type SupportedLanguage = (typeof supportedLanguages)[number];
// Use cookie language if available, otherwise detect from browser
const preferredLanguage =
cookieLanguage && supportedLanguages.includes(cookieLanguage as SupportedLanguage)
? cookieLanguage
: acceptLanguage
.split(',')
.map((lang) => lang.split(';')[0].trim().substring(0, 2))
.find((lang) => supportedLanguages.includes(lang as SupportedLanguage)) || 'en';
// Get the hash fragment if present
const url = new URL(Astro.request.url);
const hash = url.hash;
export const prerender = true;
---
<html>
<head>
<meta http-equiv="refresh" content="0; url=/en/aboutme" />
<script>
(function() {
// Supported languages
const supportedLanguages = ['en', 'de', 'nl', 'fr'];
// Try to get language from cookie
const cookieMatch = document.cookie.match(/preferredLanguage=([^;]+)/);
const cookieLanguage = cookieMatch ? cookieMatch[1] : null;
// Try to get language from browser
const browserLanguages = navigator.languages || [navigator.language];
let detected = 'en';
if (cookieLanguage && supportedLanguages.includes(cookieLanguage)) {
detected = cookieLanguage;
} else {
for (let i = 0; i < browserLanguages.length; i++) {
const lang = browserLanguages[i].slice(0,2);
if (supportedLanguages.includes(lang)) {
detected = lang;
break;
}
}
}
// Redirect to the language-specific aboutme page
return Astro.redirect(`/${preferredLanguage}/aboutme${hash}`);
---
const hash = window.location.hash || '';
window.location.replace('/' + detected + '/aboutme' + hash);
})();
</script>
<title>Redirecting...</title>
</head>
<body>
<noscript>
<meta http-equiv="refresh" content="0; url=/en/aboutme" />
<p>If you are not redirected, <a href="/en/aboutme">click here</a>.</p>
</noscript>
</body>
</html>