-
Notifications
You must be signed in to change notification settings - Fork 2
/
middleware.ts
45 lines (35 loc) · 1.21 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
import { match as matchLocale } from "@formatjs/intl-localematcher";
import Negotiator from "negotiator";
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { DEFAULT_LOCALE, LOCALES } from "./lib/constants";
function getLocale(request: NextRequest): string | undefined {
const negotiatorHeaders: Record<string, string> = {};
request.headers.forEach((value, key) => (negotiatorHeaders[key] = value));
const languages = new Negotiator({ headers: negotiatorHeaders }).languages(
LOCALES
);
const locale = matchLocale(languages, LOCALES, DEFAULT_LOCALE);
return locale;
}
export function middleware(request: NextRequest) {
const pathname = request.nextUrl.pathname;
if (/\.(.*)$/.test(pathname)) {
return;
}
const pathnameIsMissingLocale = LOCALES.every(
(locale) => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
);
if (pathnameIsMissingLocale) {
const locale = getLocale(request);
return NextResponse.redirect(
new URL(
`/${locale}${pathname.startsWith("/") ? "" : "/"}${pathname}`,
request.url
)
);
}
}
export const config = {
matcher: ["/((?!api|_next/static|_next/image).*)"],
};