Next.js中间件匹配器否定路径



我在Next.js项目上有一个中间件,我想否定我的/api/*路由。

换句话说,除了以/api/开头的任何路由之外,我希望中间件能为每个路由运行。我在文档中找不到一个例子。

我该如何实现这一点(当然,不需要逐一编写所有包含的路由(?

看起来中间件文档已经更新,以解决类似的问题。

nextjs中间件文档

export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - static (static files)
* - favicon.ico (favicon file)
*/
'/((?!api|static|favicon.ico).*)',
],
}

您不能使用matcher来完成此操作,因为它只接受简单的路径模式,因此您需要使用条件语句:

export function middleware(request: NextRequest) {
if (request.nextUrl.pathname.startsWith('/api/')) {
return NextResponse.next()
}
// your middleware logic
}

这可能有助于

const matcherRegex = new RegExp('^(?!/(?:_next/static|favicon\.ico|swc\.js|api)(?:/|$))');
export function middleware(request: NextRequest){
const isMiddlewareAllowed = matcherRegex.test(pathname)
if (isMiddlewareAllowed) {
//...
}else return
}

最新更新