如何在Next.js 13中用Middleware包裹全应用并排除/auth路由?
配置Next.js Middleware实现未认证跳转登录的路由匹配
我需要用Middleware包裹整个应用,当用户未认证时引导至登录页面,因此需要让Middleware匹配除/auth外的所有路由。
官方文档给出的示例配置如下:
export const config = { matcher: [ /* * Match all request paths except for the ones starting with: * - api (API routes) * - _next/static (static files) * - _next/image (image optimization files) * - favicon.ico (favicon file) */ '/((?!api|_next/static|_next/image|favicon.ico).*)', ], }
我自己编写的配置为:
export const config = { matcher: ['/((?!auth).*)'], };
配置优化建议
当前配置可以实现匹配除/auth开头的所有路由,但忽略了官方示例中排除的静态资源和API路由,可能引发以下问题:
- 静态文件(如
_next/static下的资源)、图片优化请求(_next/image)会被Middleware拦截,拖慢页面加载速度 - API路由请求也会被拦截,可能破坏后端接口的正常调用
建议在现有配置基础上,补充官方示例中需要排除的路径,调整后的配置如下:
export const config = { matcher: [ '/((?!auth|api|_next/static|_next/image|favicon.ico).*)', ], };
这样既保证了未认证用户访问非/auth路由时会被引导至登录页,又不会影响静态资源和API路由的正常访问。
内容的提问来源于stack exchange,提问作者RockoCH
相关产品推荐
相关产品推荐

