-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
70 lines (59 loc) · 1.96 KB
/
proxy.ts
File metadata and controls
70 lines (59 loc) · 1.96 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { i18n } from "@/i18n/config";
function getLocale(request: NextRequest): string {
// Check Accept-Language header
const acceptLanguage = request.headers.get("accept-language");
if (acceptLanguage) {
// Parse Accept-Language and find best match
const preferredLocales = acceptLanguage
.split(",")
.map((lang) => {
const [locale, quality] = lang.trim().split(";q=");
return {
locale: locale.trim().toLowerCase(),
quality: quality ? parseFloat(quality) : 1,
};
})
.sort((a, b) => b.quality - a.quality);
for (const { locale } of preferredLocales) {
// Exact match
const exactMatch = i18n.locales.find((l) => l === locale);
if (exactMatch) return exactMatch;
// Language-only match (e.g., "en-US" -> "en")
const langOnly = locale.split("-")[0];
const partialMatch = i18n.locales.find((l) => l === langOnly);
if (partialMatch) return partialMatch;
}
}
return i18n.defaultLocale;
}
export function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;
// Check if pathname already has a supported locale
const pathnameHasLocale = i18n.locales.some(
(locale) =>
pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
);
if (pathnameHasLocale) return;
// Skip internal paths and static files
if (
pathname.startsWith("/_next") ||
pathname.startsWith("/api") ||
pathname.startsWith("/sw.js") ||
pathname.startsWith("/manifest") ||
pathname.includes(".")
) {
return;
}
// Redirect to locale-prefixed path
const locale = getLocale(request);
request.nextUrl.pathname = `/${locale}${pathname}`;
return NextResponse.redirect(request.nextUrl);
}
export const config = {
matcher: [
// Skip internal paths (_next), API routes, and static files
"/((?!_next|api|.*\\..*).*)",
],
};