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.

Bobby Iliev
Site Moderator
Site Moderator badge
May 20, 2021
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

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel