Fix: restore redirect to the user's preferred locale

Users were no longer sent to their preferred locale. `LocaleRedirector` was emptied in `115fa5aca` after its previous versions caused repeated redirects, and nothing replaced it.

**Cause**
- The earlier logic compared the best locale (a string) against the current locale entry (an object), so the check was always true on non-default locale pages
- That made the redirect fire repeatedly, which led to the logic being removed entirely

**Changes**
- Derive the current locale from the URL, treating the default locale as unprefixed to match how pages are generated
- Redirect only when the best locale differs from the current locale, so it stops after one hop
- Redirect users with a saved `preferred-locale` from any page
- Redirect users without a saved preference from default-locale URLs only, using their browser language, so shared locale links are respected
- Preserve the rest of the path when swapping the locale prefix
- Skip `/api` paths
This commit is contained in:
Mark Greene committed 2026-10-04 19:47:20 +13:00
1 parent 067c9cb267
commit aaf0e52be4
1 file changed
+27
@@ -1,3 +1,30 @@
<script> <script>
import locales from "@blitzkit/i18n/locales.json";
import { getBestLocale } from "../core/i18n/getBestLocale";
const pathname = window.location.pathname;
const isAPI = pathname.startsWith("/api");
const hasPreference = localStorage.getItem("preferred-locale") !== null;
const bestLocale = getBestLocale();
const currentLocale =
locales.supported.find(
({ locale }) =>
locale !== locales.default &&
(pathname === `/${locale}` || pathname.startsWith(`/${locale}/`)),
)?.locale ?? locales.default;
if (
!isAPI &&
bestLocale !== currentLocale &&
(hasPreference || currentLocale === locales.default)
) {
const rawPath =
currentLocale === locales.default
? pathname
: pathname.slice(`/${currentLocale}`.length) || "/";
window.location.pathname = `${
bestLocale === locales.default ? "" : `/${bestLocale}`
}${rawPath}`;
}
</script> </script>