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

Next.js中使用getServerSideProps发起请求时cookies未发送到服务器是什么原因?

问题原因
  • getServerSideProps 运行在Next.js的服务端环境,而非用户浏览器环境,axios的withCredentials: true配置仅对浏览器端请求生效,作用是让浏览器自动携带存储的Cookie,服务端运行axios时没有浏览器的Cookie存储池,不会自动挂载Cookie。
  • 用户的Cookie存储在本地浏览器中,只有用户发起页面请求时会把Cookie带到Next.js的服务端,你需要手动从getServerSideProps的入参上下文里提取到用户的Cookie,再挂载到axios的请求头中传递给后端接口。
解决方案

修改getServerSideProps代码,手动传递Cookie:

export async function getServerSideProps(context) {
  // 从上下文的请求对象中提取用户携带的Cookie
  const userCookie = context.req.headers.cookie || ''
  const res = await axios.get("http://localhost:5000/api/auth", {
    headers: {
      Cookie: userCookie
    },
    withCredentials: true
  });
  const data = res.data;
  return { props: { data } }
}
  • 配置后你的后端JwtStrategy就能正常从request.cookies里取到access字段,和浏览器端发请求的逻辑一致。
  • 保留withCredentials: true不影响服务端请求,同时如果这段请求逻辑复用到前端场景也能正常生效。

内容的提问来源于stack exchange,提问作者Овов Очоы

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 11:45:03