Question

Secure Cookies not working, despite successful HTTPS connection

Hi :)

I am trying to debug my express server. I have a reverse proxy set up with NGINX and Let’s Encrypt. I am able to successfully connect using HTTPS. I get the green lock and it says ‘Connection secure’.

I am using session-based auth with express-sessions. My cookies work perfectly when the secure flag is not set. The moment I set secure to true my cookies gets rejected. Not sure why this is, I have trust-proxy set up and my connection is secure. Any ideas?

Here is a sample of the logs I am getting: “Some cookies are misusing the recommended “SameSite“ attribute” “Cookie “sid” has been rejected because it is already expired.”

And here is my cookie setup:

if (process.env.NODE_ENV === "production") {
  app.set('trust proxy', 1)
}

app.use(
  session({
    name: "sid",
    resave: false,
    saveUninitialized: false,
    secret: process.env.SESSION_SECRET,
    cookie: {
      domain: process.env.BASE_URL,
      path: "/",
      sameSite: "strict",
      secure: process.env.NODE_ENV === "production" ? true : false,
      maxAge: 1000 * 60 * 60 * 2, // 2 hours
    },
    store: MongoStore.create({
      client: db.getClient(),
      ttl: 60 * 60 * 2, // 2 hours, in seconds
      touchAfter: 24 * 3600, // time period in seconds
      crypto: {
        secret: process.env.STORE_SECRET,
      },
    }),
  })
);

Like I mentioned, no logs or errors once I take out secure (i.e. if I don’t see my NODE_ENV to “production”)

Thank you in advance.

Show comments

Submit an answer

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Accepted Answer

Hi there,

Could you also share the Nginx server block that you are using here?

I could suggest adding the following to your reverse proxy configuration:

proxy_set_header X-Forwarded-Proto $scheme;

Regards, Bobby

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in Q&A, subscribe to topics of interest, and get courses and tools that will help you grow as a developer and scale your project or business.