-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmiddleware.ts
More file actions
35 lines (30 loc) · 1.16 KB
/
middleware.ts
File metadata and controls
35 lines (30 loc) · 1.16 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
import { NextRequest, NextResponse } from "next/server";
import { match } from "@formatjs/intl-localematcher";
import Negotiator from "negotiator";
export const DEFAULT_LOCALE = "en";
export const SUPPORTED_LOCALES = ["en"];
export function middleware(request: NextRequest) {
// Check if there is any supported locale in the pathname
const pathname = request.nextUrl.pathname;
const pathnameIsMissingLocale = SUPPORTED_LOCALES.every(
(locale) =>
!pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`
);
// Redirect if there is no locale
if (pathnameIsMissingLocale) {
const negotiatorHeaders: Negotiator.Headers = {};
request.headers.forEach((value, key) => {
negotiatorHeaders[key] = value;
});
const languages = new Negotiator({
headers: negotiatorHeaders,
}).languages();
const locale = match(languages, SUPPORTED_LOCALES, DEFAULT_LOCALE);
return NextResponse.redirect(
new URL(`/${locale}/${pathname}`, request.url)
);
}
}
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};