How to use matcher in Next JS middleware

Lor*_*een 5 middleware matcher next.js

I am trying to use matcher in my Next js middleware but documentation doesnt say much on how to implement the functionality.

All it shows is this without explaining which file it goes in or how to use the config in the middleware file:

  export const config = {
  matcher: '/about/:path*',
}
Run Code Online (Sandbox Code Playgroud)

Does anyone have a working example of how to set up the matcher for a middleware file in Next js?

Thank you.

Moe*_*nia 1

1.与配置匹配:

\n

您必须Named export从中间件文件中导出一个名为 config 的对象 ():

\n
middleware.js || middleware.ts\n
Run Code Online (Sandbox Code Playgroud)\n

\r\n
\r\n
middleware.js || middleware.ts\n
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n

2.基于文件的匹配:

\n

\r\n
\r\n
//middleware.js\n\nexport function middleware(request: NextRequest) {\n  return NextResponse.redirect(new URL(\'/about-2\', request.url))\n}\n\nexport const config = {\n  matcher: \'/about/:path*\',\n}
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n

  • 从12.2(中间件稳定版本)开始,基于文件的中间件匹配不起作用。只有与“pages”目录处于同一级别的“middleware”文件才会运行。 (6认同)