-
Notifications
You must be signed in to change notification settings - Fork 1
/
middleware.ts
62 lines (50 loc) · 1.7 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
53
54
55
56
57
58
59
60
61
62
import { NextRequest, NextResponse } from "next/server";
let locales = ["en", "zh"];
let defaultLocale = "zh";
// Get the preferred locale, similar to the above or using a library
function getLocale(request: NextRequest) {
// 首先检查cookie中是否存在locale
const cookieLocale = request.cookies.get('NEXT_LOCALE')?.value;
// 如果cookie中的locale是有效的,则使用它
if (cookieLocale && locales.includes(cookieLocale)) {
return cookieLocale;
}
// 如果cookie中没有有效的locale,返回默认值
return defaultLocale;
}
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
const pathnameHasLocale = locales.some(
(locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
);
if (pathnameHasLocale) {
const headers = new Headers(request.headers);
const locale = pathname.split('/')[1];
headers.set("x-current-lang", locale);
const response = NextResponse.next({ request: { headers } });
response.cookies.set('NEXT_LOCALE', locale, {
path: '/',
maxAge: 60 * 60 * 24 * 365,
sameSite: 'strict'
});
return response;
}
// 获取locale(现在会优先使用cookie中的值)
const locale = getLocale(request);
request.nextUrl.pathname = `/${locale}${pathname}`;
const response = NextResponse.redirect(request.nextUrl);
response.cookies.set('NEXT_LOCALE', locale, {
path: '/',
maxAge: 60 * 60 * 24 * 365,
sameSite: 'strict'
});
return response;
}
export const config = {
matcher: [
// Skip all internal paths (_next)
"/((?!_next|svgs|images|constants|favicon).*)",
// Optional: only run on root (/) URL
// '/'
],
};