-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
48 lines (38 loc) · 1.28 KB
/
Copy pathproxy.ts
File metadata and controls
48 lines (38 loc) · 1.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import { NextRequest, NextResponse } from "next/server";
import { defaultLocale, isValidLocale, locales } from "@/lib/i18n/config";
function detectLocale(request: NextRequest): string {
const acceptLanguage = request.headers.get("accept-language");
if (!acceptLanguage) return defaultLocale;
const preferred = acceptLanguage
.split(",")
.map((part) => part.split(";")[0].trim());
for (const lang of preferred) {
if (isValidLocale(lang)) return lang;
const base = lang.split("-")[0];
const match = locales.find((locale) => locale.split("-")[0] === base);
if (match) return match;
}
return defaultLocale;
}
export function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;
if (
pathname.startsWith("/_next") ||
pathname.startsWith("/api") ||
pathname.includes(".")
) {
return NextResponse.next();
}
const segments = pathname.split("/");
const maybeLocale = segments[1];
if (isValidLocale(maybeLocale)) {
return NextResponse.next();
}
const locale = detectLocale(request);
const targetPath = pathname === "/" ? `/${locale}` : `/${locale}${pathname}`;
const newUrl = new URL(targetPath, request.url);
return NextResponse.redirect(newUrl);
}
export const config = {
matcher: ["/((?!_next|api|.*\\..*).*)"],
};