Next.js中间件重定向至localhost而非127.0.0.1致认证失效
我正在开发一个用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
相关产品推荐
相关产品推荐

