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

NextJS中getServerSideProps发起请求时如何携带cookies

问题原因

getServerSideProps 运行在 Node.js 服务端环境,你配置的 withCredentials: true 是浏览器端专属的请求配置,仅对客户端(浏览器侧)发起的请求生效。服务端发起请求时没有浏览器自动携带当前域名 Cookie 的机制,所以你的后端接口收到的 Cookie 为空。
而 useEffect 中的请求是在用户浏览器中执行的,浏览器会自动管理同域下的 Cookie,搭配 withCredentials: true 就会自动把 Cookie 附在请求头中,因此能正常拿到数据。

解决方法

你只需要手动把 getServerSideProps 中从用户请求拿到的 req.cookies 拼接成标准 Cookie 头,传给服务端发起的请求即可:

// 工具函数:将Cookie对象序列化为请求头所需的字符串格式
const serializeCookies = (cookiesObj) => {
  return Object.entries(cookiesObj)
    .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
    .join('; ')
}

export async function getServerSideProps({req, res}) {
    console.log(1, req.cookies)
    
    const cookieStr = serializeCookies(req.cookies)
    const response = await $api.get(`/store/profile/user`, {
      withCredentials: true,
      headers: {
        // 手动注入Cookie头
        Cookie: cookieStr
      }
    })
    
    return { props: {} }
}

额外注意

如果你调用的后端接口会更新Cookie(比如你的刷新Token接口会返回新的refreshToken),你还需要手动把接口返回的set-cookie头透传给客户端响应,否则用户本地的Cookie不会更新:

const response = await $api.get(`/store/profile/user`, {
  withCredentials: true,
  headers: {
    Cookie: cookieStr
  }
})

// 透传后端返回的Set-Cookie到客户端
if (response.headers['set-cookie']) {
  res.setHeader('Set-Cookie', response.headers['set-cookie'])
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 22:45:04