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

Can*_*ğlu 6 javascript middleware routes node.js next.js

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

换句话说,我希望中间件为每个路由运行,除了以/api/. 我在文档中找不到示例。

我如何实现这一点(当然,无需一一编写所有包含的路线)?

小智 11

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

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).*)',
  ],
}
Run Code Online (Sandbox Code Playgroud)


jed*_*ylo 7

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

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

 // your middleware logic
}
Run Code Online (Sandbox Code Playgroud)