-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
68 lines (59 loc) · 1.97 KB
/
proxy.ts
File metadata and controls
68 lines (59 loc) · 1.97 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
import { match } from "@formatjs/intl-localematcher";
import Negotiator from "negotiator";
import { NextResponse } from "next/server";
import {
SUPPORTED_LOCALES,
DEFAULT_LOCALE,
LOCALE_COOKIE_NAME,
} from "@/constants/app";
import type { Locale } from "@/types";
const locales = [...SUPPORTED_LOCALES];
const defaultLocale = DEFAULT_LOCALE;
function getLocale(request: Request): string {
// Check for saved locale preference in cookie
const cookieHeader = request.headers.get("cookie") || "";
const localeCookiePattern = new RegExp(`${LOCALE_COOKIE_NAME}=([^;]+)`);
const localeCookieMatch = cookieHeader.match(localeCookiePattern);
if (
localeCookieMatch &&
localeCookieMatch[1] &&
(locales as readonly string[]).includes(localeCookieMatch[1])
) {
return localeCookieMatch[1] as Locale;
}
// Fall back to browser language preferences
const headers = new Headers(request.headers);
const acceptLanguage = headers.get("accept-language") || "";
const headersObject = { "accept-language": acceptLanguage };
const languages = new Negotiator({ headers: headersObject }).languages();
return match(languages, locales, defaultLocale);
}
export function proxy(request: Request) {
const { pathname } = new URL(request.url);
// Skip API routes and internal Next.js paths
if (
pathname.startsWith("/api/") ||
pathname.startsWith("/_next/") ||
pathname.startsWith("/favicon.ico")
) {
return;
}
// Check if there is any supported locale in the pathname
const pathnameHasLocale = locales.some(
(locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
);
if (pathnameHasLocale) {
return;
}
// Redirect if there is no locale
const locale = getLocale(request);
const newUrl = new URL(request.url);
newUrl.pathname = `/${locale}${pathname}`;
return NextResponse.redirect(newUrl);
}
export const config = {
matcher: [
// Skip all internal paths (_next)
"/((?!_next|api|favicon.ico).*)",
],
};