Next.js 13中间件无Cookie时重定向登录页面解决循环请求问题
解决Next.js中间件重定向循环问题
你的代码出现持续循环请求的核心原因是:中间件会拦截所有请求,包括重定向后的/login请求。当用户被转到/login后,中间件依然检测不到token Cookie,会再次触发重定向,形成无限循环。
修复方案
在中间件中添加判断逻辑,排除/login路由,不对该路径执行认证校验:
import { NextResponse } from "next/server"; export function middleware(req) { const currentPath = req.nextUrl.pathname; // 跳过login路由的校验,避免循环重定向 if (currentPath === "/login") { return NextResponse.next(); } const token = req.cookies.get("token")?.value; // 无token时重定向到登录页 if (!token) { const loginUrl = req.nextUrl.clone(); loginUrl.pathname = "/login"; return NextResponse.redirect(loginUrl); } // 有token时正常放行请求 return NextResponse.next(); }
扩展优化
如果还有其他不需要认证的公共路由(比如首页、静态资源路径等),可以用数组批量排除:
import { NextResponse } from "next/server"; // 定义不需要校验的公共路由 const publicPaths = ["/login", "/", "/static", "/favicon.ico"]; export function middleware(req) { const currentPath = req.nextUrl.pathname; if (publicPaths.includes(currentPath)) { return NextResponse.next(); } const token = req.cookies.get("token")?.value; if (!token) { const loginUrl = req.nextUrl.clone(); loginUrl.pathname = "/login"; return NextResponse.redirect(loginUrl); } return NextResponse.next(); }
内容的提问来源于stack exchange,提问作者Ranganath MD
相关产品推荐
相关产品推荐

