-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
90 lines (71 loc) · 2.28 KB
/
Copy pathproxy.ts
File metadata and controls
90 lines (71 loc) · 2.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import { NextResponse, type NextRequest } from "next/server";
import {
getLocaleFromPath,
getRoutableLocales,
isRoutableLocale,
LOCALE_COOKIE_NAME,
matchPreferredLocale,
REQUEST_LOCALE_HEADER,
} from "@/lib/locale";
const routableLocalePattern = new RegExp(
`^/(${getRoutableLocales().join("|")})(?=/|$)`,
);
const internalLocalePattern = new RegExp(
`^/i18n/(${getRoutableLocales().join("|")})(?=/|$)`,
);
function getRequestLocale(request: NextRequest) {
const pathnameLocale = getLocaleFromPath(request.nextUrl.pathname);
if (pathnameLocale) {
return pathnameLocale;
}
const cookieLocale = request.cookies.get(LOCALE_COOKIE_NAME)?.value;
if (cookieLocale) {
return matchPreferredLocale(cookieLocale);
}
return matchPreferredLocale(request.headers.get("accept-language"));
}
function withLocaleHeader(request: NextRequest, locale: string) {
const headers = new Headers(request.headers);
headers.set(REQUEST_LOCALE_HEADER, locale);
return headers;
}
export function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;
const internalMatch = pathname.match(internalLocalePattern);
if (internalMatch) {
const locale = internalMatch[1];
const rest = pathname.replace(new RegExp(`^/i18n/${locale}`), "") || "/";
const url = request.nextUrl.clone();
url.pathname = `/${locale}${rest === "/" ? "" : rest}`;
return NextResponse.redirect(url, 308);
}
const requestLocale = getRequestLocale(request);
const match = pathname.match(routableLocalePattern);
if (match) {
const locale = match[1];
if (isRoutableLocale(locale)) {
const rest = pathname.replace(new RegExp(`^/${locale}`), "");
const url = request.nextUrl.clone();
url.pathname = `/i18n/${locale}${rest}`;
const response = NextResponse.rewrite(url, {
request: {
headers: withLocaleHeader(request, locale),
},
});
response.cookies.set(LOCALE_COOKIE_NAME, locale, {
path: "/",
maxAge: 60 * 60 * 24 * 365,
sameSite: "lax",
});
return response;
}
}
return NextResponse.next({
request: {
headers: withLocaleHeader(request, requestLocale),
},
});
}
export const config = {
matcher: ["/((?!_next|api|favicon.ico|robots.txt|sitemap.xml).*)"],
};