最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Next.js middleware matcher negate path - Stack Overflow

programmeradmin3浏览0评论

I have a middleware on a Next.js project, and I want to negate my /api/* route.

In other words, I want middleware to run for every route except anything that starts with /api/. I couldn't find an example in the docs.

How do I achieve that (of course, without writing all included routes one by one)?

I have a middleware on a Next.js project, and I want to negate my /api/* route.

In other words, I want middleware to run for every route except anything that starts with /api/. I couldn't find an example in the docs.

How do I achieve that (of course, without writing all included routes one by one)?

Share Improve this question edited Aug 22, 2022 at 8:25 jedrzej.kurylo 40.9k10 gold badges106 silver badges112 bronze badges asked Aug 19, 2022 at 10:41 Can PoyrazoğluCan Poyrazoğlu 34.8k54 gold badges206 silver badges423 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 14

Looks like the middleware docs have been updated to account for something like this.

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

You cannot do this with matcher, because it only accepts simple path patterns, therefore you'll need to use conditional statement:

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

 // your middleware logic
}

It might help

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
}
发布评论

评论列表(0)

  1. 暂无评论