首页 > 解决方案 > 如何使用下一个 js 和 firebase 在 getServerSideProps 中检索会话 cookie

问题描述

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

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?

标签: expressnext.js

解决方案


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


推荐阅读