Files
wm-projekt/middleware.ts
2026-07-01 10:56:47 -05:00

43 lines
1.2 KiB
TypeScript

import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
const SUPPORTED_LOCALES = ["en", "de"] as const;
function getLocale(request: NextRequest): string {
const acceptLang = request.headers.get("accept-language") ?? "";
const preferred = acceptLang.split(",")[0]?.trim().slice(0, 2);
if (preferred && SUPPORTED_LOCALES.includes(preferred as any)) return preferred;
return "en";
}
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
// API routes and static files pass through
if (
pathname.startsWith("/api/") ||
pathname.includes(".") ||
pathname.startsWith("/_next")
) {
return NextResponse.next();
}
// Check if pathname already has a supported locale
const hasLocale = SUPPORTED_LOCALES.some(
(l) => pathname === `/${l}` || pathname.startsWith(`/${l}/`),
);
if (!hasLocale) {
const locale = getLocale(request);
const url = request.nextUrl.clone();
url.pathname = `/${locale}${pathname === "/" ? "" : pathname}`;
return NextResponse.redirect(url);
}
return NextResponse.next();
}
export const config = {
matcher: ["/((?!_next|api|favicon.ico).*)"],
};