首页 > 解决方案 > 如何在 getServerSideProps 中使用 fetch 转发 cookie?

问题描述

我正在为我的应用程序使用 Nextjs。在页面上,我想从经过身份验证的 API 端点('/api/profile')获取数据。

我尝试了以下方法,但没有成功:

export async function getServerSideProps(ctx) {
  const { req, res } = ctx
  const cookies = cookie.parse(req.headers.cookie ?? '')
  const mycookie = cookies[MY_COOKIE] // mycookie exists and is set correctly

  if (mycookie) {
    const response = await fetch(process.env.SERVER_HOST+'/api/profile', {
      credentials: 'same-origin' // I tried with and without this, also tried "include" instead
    })

  ...

我有两个问题:

注意:我的 cookie 是httpOnly.

标签: reactjscookiesnext.js

解决方案


Turns out I'm allowed to manually forward the cookie through:

if (mycookie) {
  const response = await fetch(process.env.SERVER_HOST+'/api/profile', {     
    headers: {
      cookie: mycookie
    }
  })
...

推荐阅读