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

Next.js中间件重定向至localhost而非127.0.0.1致认证失效

Next.js中间件重定向时Host从127.0.0.1变为localhost导致Cookie失效问题

我正在开发一个用Next.js中间件实现认证的项目,应用运行在127.0.0.1:3000,后端(FastAPI)配置为127.0.0.1设置Cookie。中间件触发重定向前一切正常,但当中间件将已认证用户重定向到其他路由时,浏览器重定向响应里的Location头会从http://127.0.0.1:3000变成http://localhost:3000。由于localhost和127.0.0.1被视为不同域名,绑定到127.0.0.1的Cookie不会随请求发送,用户呈现未认证状态,最终被重定向到localhost的登录页,而非预期的127.0.0.1页面。

注意事项

  • Cookie已正确设置为127.0.0.1,属性为:domain=127.0.0.1 SameSite=Lax HttpOnly=true
  • 尽管在中间件中明确用127.0.0.1构建重定向URL,响应的Location头仍显示http://localhost:3000

中间件代码(middleware.ts)

import { NextResponse } from 'next/server';

export async function middleware(request) {
    const protocol = request.nextUrl.protocol || 'http';
    const host = request.headers.get('host'); // 获取实际主机地址
    const redirectUrl = `${protocol}//${host}/services/patient/search`;

    const token = request.cookies.get("token")?.value;

    if (token) {
      console.log("User is authenticated. Redirecting to:", redirectUrl);
      return NextResponse.redirect(redirectUrl);
    }

    console.log("User is not authenticated. Proceeding...");
    return NextResponse.next();
}

通过request.headers.get('host')动态构建的redirectUrl能正确解析为127.0.0.1:3000,但浏览器仍然重定向到localhost:3000。

已尝试的解决方案

  • 使用request.headers.get('host')动态构建重定向URL以匹配请求主机
  • 更新package.json中的dev脚本,将Next.js开发服务器显式绑定到127.0.0.1:"dev": "next dev -H 127.0.0.1 -p 3000"
  • 清除localhost和127.0.0.1的Cookie及浏览器缓存
  • 确保后端Cookie显式设置domain=127.0.0.1
  • 使用无痕模式测试以排除缓存问题

内容的提问来源于stack exchange,提问作者UmmB

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 07:07:40