-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
72 lines (55 loc) · 2.13 KB
/
proxy.ts
File metadata and controls
72 lines (55 loc) · 2.13 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
// next
import { NextResponse, NextRequest } from "next/server";
// accept-language
import acceptLanguage from "accept-language";
// i18n
import { fallbackLng, languages, cookieName } from "@i18n/settings";
acceptLanguage.languages(languages);
export const config = {
matcher: ["/((?!api|_next/static|_next/image|assets|favicon.ico|sw.js|site.webmanifest|sitemap.xml|robots.txt).*)"]
};
export function proxy(req: NextRequest) {
const { pathname, search } = req.nextUrl;
if (pathname.indexOf("icon") > -1 || pathname.indexOf("chrome") > -1) {
return NextResponse.next();
}
const lng = getLanguage(req);
let response = NextResponse.next();
let target = `${pathname}${search}`;
let mustRedirect = false;
if (lng === fallbackLng) {
if (target === `/${fallbackLng}` || target.startsWith(`/${fallbackLng}/`)) {
target = target.replace(`/${fallbackLng}`, target === `/${fallbackLng}` ? "/" : "");
mustRedirect = true;
}
if (mustRedirect) {
response = NextResponse.redirect(new URL(target, req.url));
}
if (!pathname.startsWith(`/${fallbackLng}/`) && pathname !== `/${fallbackLng}` && lng === fallbackLng) {
response = NextResponse.rewrite(new URL(`/${fallbackLng}${pathname}${search}`, req.url));
}
} else {
if (!languages.some((lang) => lang === pathname?.split("/")[1]) && !pathname.startsWith("/_next")) {
target = `/${lng}${pathname}${search}`;
response = NextResponse.redirect(new URL(`${target}`, req.url));
}
}
response.cookies.set(cookieName, lng);
return response;
}
function getLanguage(req: NextRequest) {
let lng: string | null | undefined = req.nextUrl.pathname?.split("/")[1];
if (!languages.some(lang => lang === lng)) {
lng = null;
}
if (!lng && req.cookies.has(cookieName)) {
lng = req.cookies.get(cookieName)?.value;
}
if (!lng && req.headers.get("Accept-Language")) {
lng = acceptLanguage.get(req.headers.get("Accept-Language"));
}
if (!lng) {
lng = fallbackLng;
}
return lng;
}