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

pb3s4cty  于 2023-06-22  发布在  其他
关注(0)|答案(3)|浏览(119)

我在Next.js项目中有一个中间件,我想否定我的/api/*路由。
换句话说,我希望中间件能为除了以/api/开头的路由之外的所有路由运行。我在docs中找不到一个例子。
我如何实现这一点(当然,不需要一个接一个地写所有 included 路由)?

quhf5bfb

quhf5bfb1#

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

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

piah890a2#

matcher不能这样做,因为它只接受简单的路径模式,所以你需要使用条件语句:

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

 // your middleware logic
}
piok6c0g

piok6c0g3#

也许会有帮助

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
}

相关问题