【问题标题】:How to retrieve session cookies in getServerSideProps using next js & firebase如何使用下一个 js 和 firebase 在 getServerSideProps 中检索会话 cookie
【发布时间】:2021-05-22 13:37:13
【问题描述】:

我在 nextjs 项目中使用 firebase 进行身份验证。我正在使用 firebase admin SDK 在一个快速后端 API 上生成一个会话 cookie,该 API 在不同端口的 localhost 上运行。

const cookie = await this.createSessionCookie(req.body.token)
    if(cookie) {
      // set cookie expiration
      const expiresIn = 60 * 60 * 24 * 5 * 1000;
      // Set cookie policy for session cookie.
      const cookieOptions = { maxAge: expiresIn, httpOnly: true, secure: true, path: '/'};
      res.cookie('session', cookie, cookieOptions);
      res.end(JSON.stringify(
        {
          "message": "User created successfully",
          "status": "success",
          "data": { result }
        }
      ));
    }

但是我无法在 nextJS 的 getServerSideProps 中检索 cookie。

export async function getServerSideProps(context) {
  const cookies = nookies.get(context)
  if (!cookies.session) {
    context.res.writeHead(302, { Location: '/auth/signin' })
    context.res.end()
  }
  return {
   props: {}
  }
}

我知道这是同源策略的结果,因为下一个应用程序和后端 API 位于 localhost 的不同端口上。有没有办法可以在下一个应用程序中检索 cookie?

【问题讨论】:

    标签: express next.js


    【解决方案1】:

    原来我需要将 cookie 选项设置为 false,因为我在本地主机上。在此之后,我能够设置 cookie。

    【讨论】:

      猜你喜欢
      • 2021-08-04
      • 2020-11-30
      • 2023-02-23
      • 1970-01-01
      • 1970-01-01
      • 2018-11-06
      • 2021-08-10
      • 1970-01-01
      • 2019-03-12
      相关资源
      最近更新 更多