Cookie 未在生产中使用 express-session 设置 [英] Cookie not set with express-session in production

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

问题描述

我的应用分为客户端和服务器.客户端是托管在 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,我使用 express-session 来实现它.这是我的快速会话配置

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)//信任第一个代理

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

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

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

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