我有一个 NextJS 中间件,我需要检查类别是否存在。如果没有,请转到 404 页面。 目录看起来像这样
pages/
├──[category_code].jsx
└── ...(other pages)
middleware.jsx
中间件正在执行,但如何在匹配器配置中匹配此路径?
这是我的中间件
import { NextResponse } from "next/server";
export async function middleware(request) {
// this is executed
}
// I need this middleware to target [category_code].jsx
export const config = {
matcher: "/pages/:path",
};
我需要这个中间件来定位 [category_code].jsx,但事实并非如此。 我试过了
/:path
/:path*
/:category_code
/[category_code]
我该怎么办?
您可以尝试在中间件中单独处理路径。匹配器可以简单地设置为除 API 路由和静态资产之外的所有内容的默认匹配器。这将为处理其他路径实例提供更大的灵活性。以下是如何执行此操作的示例:
export default async function middleware(request, response) {
const pathname = request.nextUrl.pathname;
// Check if the path is a category
if (!pathname.matches('[category_code]')) {
// throw error or redirect
return NextResponse.json({ error: 'Category Not Found' }, { status: 404 });
}
// handle other routes
}
export const config = {
matcher: ['/((?!api|_next|.*\\..*).*)'],
};