-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
48 lines (42 loc) · 1.3 KB
/
Copy pathmiddleware.ts
File metadata and controls
48 lines (42 loc) · 1.3 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
36
37
38
39
40
41
42
43
44
45
46
47
48
import createMiddleware from "next-intl/middleware";
import { locales, defaultLocale } from "./i18n";
import { NextResponse, NextRequest } from "next/server";
const intlMiddleware = createMiddleware({
locales,
defaultLocale,
localePrefix: "always",
});
export default function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;
// 根路径强制跳转到 /en,并设置 Cookie
if (pathname === "/") {
const res = NextResponse.redirect(new URL("/en", req.url));
res.cookies.set("NEXT_LOCALE", "en", {
path: "/",
maxAge: 60 * 60 * 24 * 365,
});
return res;
}
// 访问带前缀路径时同步刷新 Cookie,再交给 next-intl 处理
if (pathname.startsWith("/en")) {
const res = NextResponse.next();
res.cookies.set("NEXT_LOCALE", "en", {
path: "/",
maxAge: 60 * 60 * 24 * 365,
});
// 只调用一次中间件
return intlMiddleware(req) as NextResponse;
}
if (pathname.startsWith("/zh")) {
const res = NextResponse.next();
res.cookies.set("NEXT_LOCALE", "zh", {
path: "/",
maxAge: 60 * 60 * 24 * 365,
});
return intlMiddleware(req) as NextResponse;
}
return intlMiddleware(req) as NextResponse;
}
export const config = {
matcher: ["/((?!api|_next|images|flags|favicon.ico|sitemap.xml).*)"],
};