Files
manoon-headless/middleware.ts

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, 301);
}
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|.*\\..*).*)",
],
};