如何在Next.js中跳过/auth/signIn页面的NextAuth中间件逻辑?
解决NextAuth中间件拦截登录页导致持续加载的问题
问题分析
你当前的核心问题是:希望NextAuth中间件不对/auth/signIn页面执行校验,但保留中间件时登录页会无限加载,删除中间件则能正常访问。本质原因是**withAuth的authorized回调会优先于你的自定义中间件逻辑执行**:未登录用户访问登录页时,authorized检查到无有效用户,会自动重定向到登录页,形成循环拦截,导致页面持续加载。
另外注意你的NextAuth配置中登录页路径是/auth/signin(小写结尾),但原中间件里判断的是/auth/signIn(大写I),大小写不匹配也会导致判断失效。
解决方案
推荐两种处理方式,优先选择第一种(性能更优):
方式1:用matcher直接排除登录页
通过matcher指定中间件仅作用于非登录页的路径,让中间件完全跳过登录页的请求处理:
import { withAuth } from "next-auth/middleware"; import { NextResponse } from "next/server"; import jwt_decode from "jwt-decode"; export default withAuth( function middleware(req) { console.log("Request Path:", req.nextUrl.pathname); if (process.env.NEXT_PUBLIC_NEXTAUTH_ENABLED === "true") { const decodedToken = jwt_decode(req.nextauth?.token?.accessToken); if (!req.nextauth.user) { return; } const scope = decodedToken?.scope; const currentUrlPath = req.nextUrl.pathname; if ( !scope || (!scope.includes("studio_scope") && !scope.includes("admin_scope") && !scope.includes("superuser_scope")) ) { return new NextResponse("您没有权限!请联系系统管理员"); } if ( scope.includes("admin_scope") && ["/ontology", "/projects", "/user-management"].some((sc) => currentUrlPath?.includes(sc)) ) { return new NextResponse("您无权访问此资源!"); } if (scope.includes("studio_scope") && currentUrlPath === "/skills") { return new NextResponse("您无权访问此资源!"); } } }, { callbacks: { authorized: (params) => { return !!params.user; } }, // 仅对登录页之外的路径生效 matcher: ["/((?!auth/signin).*)"] }, );
方式2:修改authorized回调,跳过登录页校验
如果不想用matcher,可以在authorized回调中判断当前路径,若是登录页则直接放行:
import { withAuth } from "next-auth/middleware"; import { NextResponse } from "next/server"; import jwt_decode from "jwt-decode"; export default withAuth( function middleware(req) { console.log("Request Path:", req.nextUrl.pathname); if (process.env.NEXT_PUBLIC_NEXTAUTH_ENABLED === "true") { const decodedToken = jwt_decode(req.nextauth?.token?.accessToken); if (!req.nextauth.user) { return; } const scope = decodedToken?.scope; const currentUrlPath = req.nextUrl.pathname; if ( !scope || (!scope.includes("studio_scope") && !scope.includes("admin_scope") && !scope.includes("superuser_scope")) ) { return new NextResponse("您没有权限!请联系系统管理员"); } if ( scope.includes("admin_scope") && ["/ontology", "/projects", "/user-management"].some((sc) => currentUrlPath?.includes(sc)) ) { return new NextResponse("您无权访问此资源!"); } if (scope.includes("studio_scope") && currentUrlPath === "/skills") { return new NextResponse("您无权访问此资源!"); } } }, { callbacks: { authorized: (params) => { // 登录页直接放行,不校验用户 if (params.request.nextUrl.pathname === "/auth/signin") { return true; } // 其他路径校验用户是否存在 return !!params.user; } }, }, );
额外注意点
- 统一路径大小写:确保NextAuth配置里的
signIn路径和中间件里的判断路径完全一致(均为/auth/signin小写),避免因大小写不匹配导致判断失效。
内容的提问来源于stack exchange,提问作者Harish Kumar
相关产品推荐
相关产品推荐

