Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set secure cookie using heroku + node.js + express?

I have a node.js app running on the Cedar stack and I'm puzzled why secure cookies don't work.

"express": "3.0.3",
"node": ">=0.8.14",

...
app.use(express.session({
        secret : 'somesecret',
        store : // store works fine, sessions are stored
        key : 'sid',
        cookie : {
            secure : true, // it works without the secure flag (cookie is set)
            proxy : true,  // tried using this as well, no difference
            maxAge: 5184000000 // 2 months
        }
}));
...

On localhost everything works fine, but on heroku I don't seem to be able to set a secure cookie. What am I doing wrong? The docs say the load balancer terminates SSL, is it something to configure over there?
thanks a lot

like image 328
hlev Avatar asked Jan 22 '13 17:01

hlev


1 Answers

Solution

The problem was that I set proxy: true in the wrong place, it should look like as follows:

...
app.enable('trust proxy'); // optional, not needed for secure cookies
app.use(express.session({
    secret : 'somesecret',
    store : ..., // store works fine, sessions are stored
    key : 'sid',
    proxy : true, // add this when behind a reverse proxy, if you need secure cookies
    cookie : {
        secure : true,
        maxAge: 5184000000 // 2 months
    }
}));
...

Add as well app.enable('trust proxy'); suggested by @friism in case you want to use req.protocol somewhere in the Heroku hosted app.

like image 153
hlev Avatar answered Nov 16 '22 03:11

hlev