在开发Next.js项目时,可能会遇到多个中间件需要共存的情况。如果这些中间件之间存在冲突,就需要一种方式来协调它们的工作。

问题背景

我们在项目中添加了Clerk登录中间件,同时需要实现一个本地化中间件,根据请求路径中的语言参数来重定向用户。如果请求路径中没有包含语言参数,我们需要自动添加默认语言。

以下是我们原本的两个中间件:

  1. Clerk登录中间件
  2. 本地化中间件

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)(.*)'],
};

admin
Author: admin

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注