refactor: make locale handling truly centralized and robust

- Added getPathWithoutLocale() and buildLocalePath() helpers to locales.ts
- Updated Header to use centralized helpers instead of hardcoded regex
- Updated middleware to use SUPPORTED_LOCALES in matcher config
- Updated LocaleProvider to use isValidLocale() instead of hardcoded array

To add a new language now, only update:
1. SUPPORTED_LOCALES in locales.ts
2. LOCALE_CONFIG entry with label, flag, saleorLocale
3. Add translation keys to all message files

All routing now uses centralized constants - no more hardcoded locale lists.
This commit is contained in:
Unchained
2026-03-24 11:52:22 +02:00
parent 0a7c555549
commit 03becb6ce7
4 changed files with 37 additions and 26 deletions

View File

@@ -1,25 +1,29 @@
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { SUPPORTED_LOCALES, DEFAULT_LOCALE, LOCALE_COOKIE, getLocaleFromPath } from "@/lib/i18n/locales";
import { SUPPORTED_LOCALES, DEFAULT_LOCALE, LOCALE_COOKIE, getPathWithoutLocale, buildLocalePath, isValidLocale } from "@/lib/i18n/locales";
import type { Locale } from "@/lib/i18n/locales";
const OLD_SERBIAN_PATHS = ["products", "about", "contact", "checkout"];
function detectLocale(cookieLocale: string | undefined, acceptLanguage: string): Locale {
if (cookieLocale && isValidLocale(cookieLocale)) {
return cookieLocale;
}
if (acceptLanguage.includes("en")) {
return "en";
}
return DEFAULT_LOCALE;
}
export default function middleware(request: NextRequest) {
const pathname = request.nextUrl.pathname;
const cookieLocale = request.cookies.get(LOCALE_COOKIE)?.value;
const acceptLanguage = request.headers.get("accept-language") || "";
if (pathname === "/" || pathname === "") {
let locale = DEFAULT_LOCALE;
if (cookieLocale && SUPPORTED_LOCALES.includes(cookieLocale as typeof SUPPORTED_LOCALES[number])) {
locale = cookieLocale;
} else if (acceptLanguage.includes("en")) {
locale = "en";
}
const locale = detectLocale(cookieLocale, acceptLanguage);
const url = request.nextUrl.clone();
url.pathname = `/${locale}`;
url.pathname = buildLocalePath(locale, "/");
return NextResponse.redirect(url, 301);
}
@@ -28,16 +32,10 @@ export default function middleware(request: NextRequest) {
);
if (isOldSerbianPath) {
let locale = DEFAULT_LOCALE;
if (cookieLocale && SUPPORTED_LOCALES.includes(cookieLocale as typeof SUPPORTED_LOCALES[number])) {
locale = cookieLocale;
} else if (acceptLanguage.includes("en")) {
locale = "en";
}
const locale = detectLocale(cookieLocale, acceptLanguage);
const newPath = buildLocalePath(locale, pathname);
const url = request.nextUrl.clone();
url.pathname = `/${locale}${pathname}`;
url.pathname = newPath;
return NextResponse.redirect(url, 301);
}
@@ -47,7 +45,7 @@ export default function middleware(request: NextRequest) {
export const config = {
matcher: [
"/",
"/(sr|en|de|fr)/:path*",
`/${SUPPORTED_LOCALES.join("|")}/:path*`,
"/((?!api|_next|_vercel|.*\\..*).*)",
],
};