未在生产中设置带有快速会话的Cookie [英] Cookie not set with express-session in production

查看:94
本文介绍了未在生产中设置带有快速会话的Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序在客户端和服务器之间划分.客户端是在Now.sh上托管的前端Nextjs应用程序,服务器是通过Express创建并在Heroku上托管的后端应用程序,因此域是client-app.now.sh和server-app.herokuapp.com.

My app is divided between Client and Server. Client is a frontend side Nextjs app hosted on Now.sh, Server is its backend created with Express and hosted on Heroku, so the domains are client-app.now.sh and server-app.herokuapp.com .

身份验证

身份验证系统基于cookie,我正在使用快速会话来实现它.这是我的快速会话配置

Authentication system is based on cookies and I'm using express-session to achieve it. This is my express-session configuration

app.use(
  session({
    store:
      process.env.NODE_ENV === "production"
        ? new RedisStore({
            url: process.env.REDIS_URL
          })
        : new RedisStore({
            host: "localhost",
            port: 6379,
            client
          }),
    name: "sessionID",
    resave: false,
    saveUninitialized: false,
    secret: keys.SESSION,
    unset: "destroy",
    cookie: {
      domain:
        process.env.NODE_ENV === "production"
          ? ".client-app.now.sh"
          : "localhost",
      secure: process.env.NODE_ENV === "production",
      httpOnly: true,
      maxAge: 7 * 24 * 60 * 60 * 1000
    }
  })
);

Cors使用"cors"软件包设置:

Cors is set with the "cors" package:

app.use(
  cors({
    origin:
      process.env.NODE_ENV === "production"
        ? process.env.CLIENT_URL
        : "http://localhost:3000",
    credentials: true
  })
);

为客户端配置了Apollo,并将HttpLink中的凭据"设置为包含".

Client is configured with Apollo and "credentials" in HttpLink is set to "include".

问题是在开发中正确设置了具有会话ID的cookie,但在生产中未正确设置.这可能与我将客户端和服务器托管在不同域上的事实有关吗?

The problem is that cookie with session ID is correctly set in development, but not in production. Could this be related to the fact that I'm hosting client and server on different domains?

推荐答案

我的生产节点服务器位于反向代理之后.这会导致节点不信任代理,因此不会设置cookie.

I had my production node server behind a reverse proxy. This causes node to not trust the proxy and thus not set cookies.

在生产中,我必须启用对第一个代理的信任.

I had to enable trusting the first proxy when in production.

app.set('trust proxy', 1) // trust first proxy

更多信息,请查看 express-session关于该主题的文档.

More info check out express-session's docs on the topic.

这篇关于未在生产中设置带有快速会话的Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆