mirror of
https://github.com/lukevella/rallly.git
synced 2025-07-17 08:17:26 +02:00
🐛 Fix locale fallback mechanism (#1734)
This commit is contained in:
parent
eb625b946f
commit
53a957dc49
2 changed files with 13 additions and 16 deletions
|
@ -1,12 +1,9 @@
|
|||
import languages from "@rallly/languages";
|
||||
import { getPreferredLocale } from "@rallly/languages/get-preferred-locale";
|
||||
import { getPosthogBootstrapCookie } from "@rallly/posthog/utils";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
import { withAuth } from "@/auth/edge";
|
||||
|
||||
const supportedLocales = Object.keys(languages);
|
||||
|
||||
export const middleware = withAuth(async (req) => {
|
||||
const { nextUrl } = req;
|
||||
const newUrl = nextUrl.clone();
|
||||
|
@ -19,15 +16,12 @@ export const middleware = withAuth(async (req) => {
|
|||
return NextResponse.redirect(newUrl);
|
||||
}
|
||||
|
||||
const locale =
|
||||
req.auth?.user?.locale ||
|
||||
getPreferredLocale({
|
||||
const locale = getPreferredLocale({
|
||||
userLocale: req.auth?.user?.locale ?? undefined,
|
||||
acceptLanguageHeader: req.headers.get("accept-language") ?? undefined,
|
||||
});
|
||||
|
||||
if (supportedLocales.includes(locale)) {
|
||||
newUrl.pathname = `/${locale}${pathname}`;
|
||||
}
|
||||
|
||||
const res = NextResponse.rewrite(newUrl);
|
||||
res.headers.set("x-locale", locale);
|
||||
|
|
|
@ -1,14 +1,18 @@
|
|||
import { match } from "@formatjs/intl-localematcher";
|
||||
import Negotiator from "negotiator";
|
||||
import languages, { defaultLocale } from "./index";
|
||||
|
||||
const locales = Object.keys(languages);
|
||||
import { defaultLocale, supportedLngs } from "./index";
|
||||
|
||||
export function getPreferredLocale({
|
||||
userLocale,
|
||||
acceptLanguageHeader,
|
||||
}: {
|
||||
userLocale?: string;
|
||||
acceptLanguageHeader?: string;
|
||||
}) {
|
||||
if (userLocale && supportedLngs.includes(userLocale)) {
|
||||
return userLocale;
|
||||
}
|
||||
|
||||
if (!acceptLanguageHeader) {
|
||||
return defaultLocale;
|
||||
}
|
||||
|
@ -22,9 +26,8 @@ export function getPreferredLocale({
|
|||
.filter((lang) => lang !== "*");
|
||||
|
||||
try {
|
||||
return match(preferredLanguages, locales, defaultLocale);
|
||||
return match(preferredLanguages, supportedLngs, defaultLocale);
|
||||
} catch (e) {
|
||||
console.warn("Failed to match locale", e);
|
||||
return defaultLocale;
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue