-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
57 lines (46 loc) · 1.45 KB
/
proxy.ts
File metadata and controls
57 lines (46 loc) · 1.45 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
import { defaultLocale, locales } from "@/lib/i18n";
import { NextResponse, type NextRequest } from "next/server";
const PUBLIC_FILE = /\.[^/]+$/;
function getPreferredLocale(request: NextRequest) {
const header = request.headers.get("accept-language");
if (!header) return defaultLocale;
const languages = header
.split(",")
.map((part) => part.split(";")[0]?.trim())
.filter(Boolean);
for (const language of languages) {
const base = language.split("-")[0];
if (locales.includes(base as (typeof locales)[number])) {
return base as (typeof locales)[number];
}
}
return defaultLocale;
}
export function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;
if (
pathname.startsWith("/_next") ||
pathname.startsWith("/api") ||
pathname.startsWith("/favicon.ico") ||
pathname.startsWith("/sitemap.xml") ||
pathname.startsWith("/robots.txt") ||
PUBLIC_FILE.test(pathname)
) {
return;
}
const pathnameHasLocale = locales.some(
(locale) => pathname === `/${locale}` || pathname.startsWith(`/${locale}/`),
);
if (!pathnameHasLocale) {
const locale = getPreferredLocale(request);
const url = request.nextUrl.clone();
url.pathname = `/${locale}${pathname}`;
return NextResponse.redirect(url);
}
return NextResponse.next();
}
export const config = {
matcher: [
"/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt|.*\\.png$).*)",
],
};