-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.tsx
57 lines (45 loc) · 1.69 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;
let headers = { "accept-language": acceptedLanguage };
let languages = new Negotiator({ headers }).languages();
return match(languages, config.supportedLocales, config.defaultLocale);
} catch {
return config.defaultLocale;
}
}
export async function middleware(request: NextRequest) {
const config = PageBaseConfiguration();
const pathname = request.nextUrl.pathname;
const pathLocale = config.supportedLocales.find((locale) => {
return pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`;
});
if (pathname === "/" && config.startRoute && config.startRoute !== "/") {
const locale = getLocale(request);
return NextResponse.redirect(
new URL(
`/${locale}/${config.startRoute}`.replaceAll("//", "/"),
request.url,
),
);
}
// Redirect if there is no locale
if (pathLocale == null) {
const locale = getLocale(request);
return NextResponse.redirect(new URL(`/${locale}${pathname}`, request.url));
}
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).*)",
],
};