Changes: - Root page.tsx now detects browser language (Accept-Language header) and cookie preference to redirect to correct locale (/sr or /en) - Middleware handles old Serbian URLs (/products, /about, etc.) with 301 redirects to /sr/* while respecting locale cookie - Header component now includes language switcher dropdown with flag icons (Serbian and English) - Language selection sets NEXT_LOCALE cookie and persists preference Behavior: - User visits / → redirects to /sr or /en based on cookie/browser - User selects English from dropdown → cookie set, redirects to /en/* - User visits /products with en cookie → /en/products (301) - User visits /products with sr/no cookie → /sr/products (301)
54 lines
1.4 KiB
TypeScript
54 lines
1.4 KiB
TypeScript
import { NextResponse } from "next/server";
|
|
import type { NextRequest } from "next/server";
|
|
|
|
const LOCALE_COOKIE = "NEXT_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 = "sr";
|
|
|
|
if (cookieLocale && ["sr", "en", "de", "fr"].includes(cookieLocale)) {
|
|
locale = cookieLocale;
|
|
} else if (acceptLanguage.includes("en")) {
|
|
locale = "en";
|
|
}
|
|
|
|
const url = request.nextUrl.clone();
|
|
url.pathname = `/${locale}`;
|
|
return NextResponse.redirect(url, 302);
|
|
}
|
|
|
|
const oldSerbianPaths = ["products", "about", "contact", "checkout"];
|
|
const isOldSerbianPath = oldSerbianPaths.some(
|
|
(path) => pathname === `/${path}` || pathname.startsWith(`/${path}/`)
|
|
);
|
|
|
|
if (isOldSerbianPath) {
|
|
let locale = "sr";
|
|
|
|
if (cookieLocale && ["sr", "en", "de", "fr"].includes(cookieLocale)) {
|
|
locale = cookieLocale;
|
|
} else if (acceptLanguage.includes("en")) {
|
|
locale = "en";
|
|
}
|
|
|
|
const url = request.nextUrl.clone();
|
|
url.pathname = `/${locale}${pathname}`;
|
|
return NextResponse.redirect(url, 301);
|
|
}
|
|
|
|
return NextResponse.next();
|
|
}
|
|
|
|
export const config = {
|
|
matcher: [
|
|
"/",
|
|
"/(sr|en|de|fr)/:path*",
|
|
"/((?!api|_next|_vercel|.*\\..*).*)",
|
|
],
|
|
};
|