Hide the language switcher for English-only browsers; gate /zh via Accept-Language and a client cookie. Co-authored-by: Cursor <cursoragent@cursor.com>
39 lines
1.1 KiB
TypeScript
39 lines
1.1 KiB
TypeScript
import createMiddleware from "next-intl/middleware";
|
|
import { NextRequest, NextResponse } from "next/server";
|
|
import { routing } from "./i18n/routing";
|
|
import {
|
|
acceptLanguageHasChinese,
|
|
ZH_OK_COOKIE,
|
|
} from "./lib/chinese-locale";
|
|
|
|
const intlMiddleware = createMiddleware({
|
|
...routing,
|
|
localeDetection: true,
|
|
});
|
|
|
|
function requestAllowsChinese(request: NextRequest): boolean {
|
|
if (acceptLanguageHasChinese(request.headers.get("accept-language"))) {
|
|
return true;
|
|
}
|
|
return request.cookies.get(ZH_OK_COOKIE)?.value === "1";
|
|
}
|
|
|
|
export default function middleware(request: NextRequest) {
|
|
const { pathname } = request.nextUrl;
|
|
|
|
// Shared /zh links: without Chinese signals → English only
|
|
if (pathname === "/zh" || pathname.startsWith("/zh/")) {
|
|
if (!requestAllowsChinese(request)) {
|
|
const url = request.nextUrl.clone();
|
|
url.pathname = pathname.replace(/^\/zh/, "/en") || "/en";
|
|
return NextResponse.redirect(url);
|
|
}
|
|
}
|
|
|
|
return intlMiddleware(request);
|
|
}
|
|
|
|
export const config = {
|
|
matcher: ["/", "/(en|zh)/:path*", "/((?!api|_next|_vercel|.*\\..*).*)"],
|
|
};
|