🐛 Fix locale fallback mechanism (#1734)

This commit is contained in:
Luke Vella 2025-05-28 09:44:41 +01:00 committed by GitHub
parent eb625b946f
commit 53a957dc49
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 13 additions and 16 deletions

View file

@ -1,12 +1,9 @@
import languages from "@rallly/languages";
import { getPreferredLocale } from "@rallly/languages/get-preferred-locale"; import { getPreferredLocale } from "@rallly/languages/get-preferred-locale";
import { getPosthogBootstrapCookie } from "@rallly/posthog/utils"; import { getPosthogBootstrapCookie } from "@rallly/posthog/utils";
import { NextResponse } from "next/server"; import { NextResponse } from "next/server";
import { withAuth } from "@/auth/edge"; import { withAuth } from "@/auth/edge";
const supportedLocales = Object.keys(languages);
export const middleware = withAuth(async (req) => { export const middleware = withAuth(async (req) => {
const { nextUrl } = req; const { nextUrl } = req;
const newUrl = nextUrl.clone(); const newUrl = nextUrl.clone();
@ -19,15 +16,12 @@ export const middleware = withAuth(async (req) => {
return NextResponse.redirect(newUrl); return NextResponse.redirect(newUrl);
} }
const locale = const locale = getPreferredLocale({
req.auth?.user?.locale || userLocale: req.auth?.user?.locale ?? undefined,
getPreferredLocale({ acceptLanguageHeader: req.headers.get("accept-language") ?? undefined,
acceptLanguageHeader: req.headers.get("accept-language") ?? undefined, });
});
if (supportedLocales.includes(locale)) { newUrl.pathname = `/${locale}${pathname}`;
newUrl.pathname = `/${locale}${pathname}`;
}
const res = NextResponse.rewrite(newUrl); const res = NextResponse.rewrite(newUrl);
res.headers.set("x-locale", locale); res.headers.set("x-locale", locale);

View file

@ -1,14 +1,18 @@
import { match } from "@formatjs/intl-localematcher"; import { match } from "@formatjs/intl-localematcher";
import Negotiator from "negotiator"; import Negotiator from "negotiator";
import languages, { defaultLocale } from "./index"; import { defaultLocale, supportedLngs } from "./index";
const locales = Object.keys(languages);
export function getPreferredLocale({ export function getPreferredLocale({
userLocale,
acceptLanguageHeader, acceptLanguageHeader,
}: { }: {
userLocale?: string;
acceptLanguageHeader?: string; acceptLanguageHeader?: string;
}) { }) {
if (userLocale && supportedLngs.includes(userLocale)) {
return userLocale;
}
if (!acceptLanguageHeader) { if (!acceptLanguageHeader) {
return defaultLocale; return defaultLocale;
} }
@ -22,9 +26,8 @@ export function getPreferredLocale({
.filter((lang) => lang !== "*"); .filter((lang) => lang !== "*");
try { try {
return match(preferredLanguages, locales, defaultLocale); return match(preferredLanguages, supportedLngs, defaultLocale);
} catch (e) { } catch (e) {
console.warn("Failed to match locale", e);
return defaultLocale; return defaultLocale;
} }
} }