import { NextResponse } from "next/server"; import type { NextRequest } from "next/server"; 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 === "") { const locale = detectLocale(cookieLocale, acceptLanguage); const url = request.nextUrl.clone(); url.pathname = buildLocalePath(locale, "/"); return NextResponse.redirect(url, 301); } const isOldSerbianPath = OLD_SERBIAN_PATHS.some( (path) => pathname === `/${path}` || pathname.startsWith(`/${path}/`) ); if (isOldSerbianPath) { const locale = detectLocale(cookieLocale, acceptLanguage); const newPath = buildLocalePath(locale, pathname); const url = request.nextUrl.clone(); url.pathname = newPath; return NextResponse.redirect(url, 301); } return NextResponse.next(); } export const config = { matcher: [ "/", `/${SUPPORTED_LOCALES.join("|")}/:path*`, "/((?!api|_next|_vercel|.*\\..*).*)", ], };