node express, how to clear cookie after log out

Srle picture Srle · Aug 20, 2015 · Viewed 22.3k times · Source

Basically i'm doing redirect from a.example.com to www.example.com and i expect to be able to delete cookies on www.example.com (because cookie is created with .example.com as the cookie domain), but following code doesn't work.

I know that this question seems like duplicate question, i tried everything from similar question but it doesn't work. See after the code what i already tried.

Using express 3.0.3 and node 0.10.32.

express session middleware

...
var cookiedata = { 
    domain              : '.example.com',
    originalMaxAge      : null,
    httpOnly            : false
};

app.use(express.session({
        store  : ..., 
        secret : ..., 
        key    : 'express.sid', 
        cookie : cookiedata 
}));
...

logout function

function logout(req, res){
    ...

    req.session.destroy(function(){
        req.session = null;

        res.clearCookie('express.sid', { path: '/' });
        res.redirect('https://www.example.com');

    });
}

What i already tried from similar question

  1. https://github.com/strongloop/express/issues/691

So i put path : '/' in express session middleware such as:

app.use(express.session({ ..., path : '/' });

No success.

  1. https://groups.google.com/forum/#!topic/express-js/PmgGMNOzhgM
    Instead res.clearCookie i used: res.cookie('express.sid', '', {expires: new Date(1), path: '/' });

No success.

Answer

Tien Do picture Tien Do · Dec 8, 2015

This is response.clearCookie of Express.JS (file response.js at line 749).

var opts = merge({ expires: new Date(1), path: '/' }, options);
return this.cookie(name, '', opts);

If you set a breakpoint at this line you will see expires is reported at an invalid date. So instead of using response.clearCookie, just make it expire immediately like this one.

response.cookie("express.sid", "", { expires: new Date() });