-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
52 lines (46 loc) · 1.79 KB
/
middleware.ts
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
import { NextRequest, NextResponse } from "next/server";
import { match } from "@formatjs/intl-localematcher";
import Negotiator from "negotiator";
import { SupportedLocale } from "./i18n/types/Locale";
import { defaultLocale } from "./i18n/config";
import getLocaleFromPathname from "./i18n/getLocaleFromPathname";
// Get the preferred locale, similar to above or using a library
const getLocaleFromRequest = (request: NextRequest): string => {
const headers = Object.fromEntries(request.headers.entries());
const languages = new Negotiator({ headers }).languages();
return match(languages, SupportedLocale, defaultLocale);
};
export const middleware = (request: NextRequest) => {
const requestHeaders = new Headers(request.headers);
const pathname = request.nextUrl.pathname;
// Check if there is any supported locale in the pathname
const pathnameIsMissingLocale = SupportedLocale.every(
(locale) =>
!pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
);
let locale: string | null = null;
// Redirect if there is no locale
if (pathnameIsMissingLocale) {
locale = getLocaleFromRequest(request);
// e.g. incoming request is /products
// The new URL is now /en-US/products
return NextResponse.redirect(
new URL(`/${locale}/${pathname}`, request.url)
);
} else {
locale = getLocaleFromPathname(pathname);
}
requestHeaders.set("x-pathname", pathname);
requestHeaders.set("x-locale", locale);
return NextResponse.next({
request: {
headers: requestHeaders,
},
});
};
export const config = {
matcher: [
// Skip all internal paths (_next)
"/((?!api|_next/static|_next/image|favicon.png|images/|cache|robots.txt).*)",
],
};