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

未认证用户重定向至登录页后,Next.js中间件崩溃原因排查

解决Next.js中间件重定向崩溃问题

你的代码存在几个核心问题,导致重定向后中间件崩溃:

问题分析

  1. 未定义认证判断逻辑:代码里调用的isAuthenticated()没有实现,也没有从request对象中获取Cookie的逻辑,根本无法正确判断用户是否认证。
  2. 无限重定向循环:未认证用户被重定向到/auth/signin,但这个路径会被你的matcher规则匹配,中间件会再次执行重定向,反复触发导致崩溃。
  3. 硬编码地址:直接写死http://localhost:3000,部署到生产环境后会失效。
  4. 不必要的async标记:函数里没有使用await,不需要标记为async。

修复后的代码

import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";

export function middleware(request: NextRequest) {
  // 替换成你实际使用的认证Cookie名称
  const authCookie = request.cookies.get("auth-token");
  const HAS_COOKIE = !!authCookie;
  const currentPath = request.nextUrl.pathname;

  // 已认证用户访问/auth路径时,跳转至feed页
  if (HAS_COOKIE) {
    if (currentPath.startsWith("/auth")) {
      const feedUrl = new URL("/feed", request.nextUrl.origin);
      return NextResponse.redirect(feedUrl);
    }
    return NextResponse.next();
  } else {
    // 未认证用户仅在访问非/auth路径时,才跳转至登录页
    if (!currentPath.startsWith("/auth")) {
      const signInUrl = new URL("/auth/signin", request.nextUrl.origin);
      return NextResponse.redirect(signInUrl);
    }
    // 未认证但访问/auth相关页面,允许正常访问
    return NextResponse.next();
  }
}

export const config = {
  matcher: [
    "/((?!api|_next/static|_next/image|favicon.ico).*)",
  ],
};

关键修改说明

  • 正确获取Cookie:通过request.cookies.get()获取认证Cookie,确保能准确判断用户认证状态(记得替换auth-token为你项目实际的Cookie键名)。
  • 避免循环重定向:新增路径判断,未认证用户只有在访问非/auth开头的路径时才触发重定向,登录页本身不会被重复处理。
  • 动态生成跳转地址:使用request.nextUrl.origin拼接跳转路径,适配开发、生产等不同环境。
  • 移除多余async:去掉不需要的async标记,保持代码简洁。

内容的提问来源于stack exchange,提问作者vincent.tsx

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 07:55:42