You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 08:25:24