Ilo/frontend/src/proxy.ts
2026-05-03 19:51:38 +03:30

31 lines
928 B
TypeScript

import { NextResponse, type NextRequest } from "next/server";
const locales = ["fa", "en"] as const;
const defaultLocale = "fa";
function pickLocale(req: NextRequest): string {
const accept = req.headers.get("accept-language") ?? "";
const preferred = accept
.split(",")
.map((p) => p.trim().split(";")[0]!.toLowerCase().split("-")[0])
.find((tag) => (locales as readonly string[]).includes(tag));
return preferred ?? defaultLocale;
}
export function proxy(req: NextRequest) {
const { pathname } = req.nextUrl;
const hasLocale = locales.some(
(loc) => pathname === `/${loc}` || pathname.startsWith(`/${loc}/`),
);
if (hasLocale) return;
const locale = pickLocale(req);
const url = req.nextUrl.clone();
url.pathname = `/${locale}${pathname === "/" ? "" : pathname}`;
return NextResponse.redirect(url);
}
export const config = {
matcher: ["/((?!_next|api|favicon.ico|.*\\..*).*)"],
};