-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.tsx
57 lines (46 loc) · 1.75 KB
/
middleware.tsx
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 { NextResponse, type NextRequest } from "next/server";
import { match } from "@formatjs/intl-localematcher";
import Negotiator from "negotiator";
import PageBaseConfiguration from "./configuration";
function getLocale(request: NextRequest) {
const config = PageBaseConfiguration();
try {
const acceptedLanguage =
request.headers.get("accept-language") ?? undefined;
const headers = { "accept-language": acceptedLanguage };
const languages = new Negotiator({ headers }).languages();
return match(languages, config.supportedLocales, config.defaultLocale);
} catch {
return config.defaultLocale;
}
}
function redirectToLocale(request: NextRequest, locale: string, path: string) {
return NextResponse.redirect(new URL(`/${locale}${path}`, request.url));
}
export async function middleware(request: NextRequest) {
const config = PageBaseConfiguration();
const pathname = request.nextUrl.pathname;
const pathLocale = config.supportedLocales.find(
(locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`,
);
if (pathname === "/" && config.startRoute && config.startRoute !== "/") {
const locale = getLocale(request);
return redirectToLocale(
request,
locale,
`/${config.startRoute}`.replaceAll("//", "/"),
);
}
if (pathLocale == null) {
const locale = getLocale(request);
return redirectToLocale(request, locale, pathname);
}
const requestHeaders = new Headers(request.headers);
requestHeaders.set("x-locale", pathLocale);
return NextResponse.next({ request: { headers: requestHeaders } });
}
export const config = {
matcher: [
"/((?!api|_next|favicon.ico|robots.txt|sitemap.xml|appicons|backgrounds|favicons|flags|images|jumbotron|assets).*)",
],
};