问题背景
我们在项目中添加了Clerk登录中间件,同时需要实现一个本地化中间件,根据请求路径中的语言参数来重定向用户。如果请求路径中没有包含语言参数,我们需要自动添加默认语言。
以下是我们原本的两个中间件:
- Clerk登录中间件
- 本地化中间件
import { NextResponse } from "next/server";
import { clerkMiddleware } from "@clerk/nextjs/server";
let locales = ['en', 'zh'];
interface RequestWithNextUrl extends Request {
nextUrl: URL;
}
// Get the preferred locale, similar to the above or using a library
function getLocale(request: RequestWithNextUrl): string {
// Implement your locale detection logic here
return 'en'; // Placeholder implementation
}
export function middleware(request: RequestWithNextUrl) {
// Check if there is any supported locale in the pathname
const { pathname } = request.nextUrl;
const pathnameHasLocale = locales.some(
(locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
);
if (pathnameHasLocale) return;
// Redirect if there is no locale
const locale = getLocale(request);
request.nextUrl.pathname = `/${locale}${pathname}`;
// e.g. incoming request is /products
// The new URL is now /en/products
return NextResponse.redirect(request.nextUrl);
}
export const config = {
matcher: ['/((?!.*\\..*|_next).*)', '/', '/(api|trpc)(.*)'],
};