-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
32 lines (27 loc) · 1.02 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
import acceptLanguage from "accept-language";
import { locales } from "@/i18n.config";
import { NextRequest, NextResponse } from "next/server";
import { getLocale, getPathnameLocale } from "./middlewares/getLocale";
acceptLanguage.languages(Array.from(locales));
export default function middleware(req: NextRequest) {
const pathname = req.nextUrl.pathname;
// Check if there is any supported locale in the pathname
const locale = getLocale(req);
const pathnameLocale = getPathnameLocale(pathname);
// Redirect if there is no locale
if (!pathnameLocale) {
const response = NextResponse.redirect(
new URL(`/${locale}/${pathname}`, req.url)
);
response.cookies.set("NEXT_LOCALE", locale);
return response;
} else {
// Set locale in cookies
const response = NextResponse.next();
response.cookies.set("NEXT_LOCALE", pathnameLocale);
return response;
}
};
export const config = {
matcher: ["/((?!api|_next/static|blog|_next/image|fonts|images|sounds|vectors|assets|favicon.ico).*)"],
};