how to delete cookie on logout in express + passport js?

22,202

Solution 1

You can use req.session.destroy in logout route to destroy the session below is the code for reference :)

app.get('/logout', function(req,res){
 req.logOut();
 req.session.destroy(function (err) {
        res.redirect('/'); //Inside a callback… bulletproof!
    });
});

Solution 2

Please try this:

router.get('/logout', function (req, res) {
  req.logOut();
  res.status(200).clearCookie('connect.sid', {
    path: '/'
  });
  req.session.destroy(function (err) {
    res.redirect('/');
  });
});

Solution 3

I was struggling with this issue myself. Previously I tried logout and session.destroy, and none worked for me. Then I found the above answers with the clearCookie addition, and that did the trick.

However, I was wondering if those functions are at all having any effect, given that without clearCookie they didn't. So I omitted them.

Also, as status(200) is overridden by redirect (which sets status to 302), I reckoned I'd omit that too.

As for the options to clearCookie in Will59's solution, they looked like they could be the defaults anyhow, so I tried omitting them as well.

I ended up with two lines of code bellow. They worked for me with the Chrome, Firefox and Safari (the most recent versions at time of this writing).

router.get('/logout', function (req, res) {
  res.clearCookie('connect.sid');
  res.redirect('/');
});

Solution 4

pjiaquan's did not work with chromium for me, the cookie was still around. The issue comes from the res.clearCookie method, as explained in http://expressjs.com/en/api.html:

Web browsers and other compliant clients will only clear the cookie if the given options is identical to those given to res.cookie(), excluding expires and maxAge.

In my case, the solution ended up being:

router.get('/logout', function (req, res) {
  req.logOut();
  res.status(200).clearCookie('connect.sid', {
    path: '/',
    secure: false,
    httpOnly: false,
    domain: 'place.your.domain.name.here.com',
    sameSite: true,
  });
  req.session.destroy(function (err) {
    res.redirect('/');
  });
});

Solution 5

res.clearCookies is kind of messed up. As an alternative, call res.cookie again with whatever options you used to create the cookie in the first place, along with expires: new Date(1), like this:

// Use the same httpOnly, secure, sameSite settings to "delete" the cookie
res.cookie("jwt", "", {
    httpOnly: true, 
    secure: true,
    sameSite: "none",    
    expires: new Date(1)
});

Essentially you are replacing the old cookie with a new one that expires immediately.

Share:
22,202
romir
Author by

romir

about me i posses great interest in programming and learning new programming languages.

Updated on July 15, 2022

Comments

  • romir
    romir almost 2 years

    I want to "delete cookies on logout". I am not able to do that. I googled for answer and found following ways:

    1. Assign new date of expiration to cookie

      res.cookie('connect.sid', '', {expires: new Date(1), path: '/' });

    2. Delete cookie using below lines

      res.clearCookie('connect.sid', { path: '/' });

    I tried both ways individually but they do not delete the cookie.

    Here is my code:

    routes.js

    module.exports = function(app, passport, session){
        app.get('/', function(req, res)
        {
           res.render('index.ejs');
        });
    
        app.get('/login', function(req,res){
         res.render('login.ejs',{message:req.flash('loginMessage')});
        });
    
    
        app.get('/signup',checkRedirect , function(req, res) {
            res.render('signup.ejs',{message: req.flash('signupMessage')});
        });
        app.get('/profile', isLoggedIn, function(req,res) {
            res.render('profile.ejs', {
                user :req.user
            });
        });
        app.post('/signup', passport.authenticate('local-signup', {
            successRedirect : '/profile',
            failureRedirect : '/signup',
            failureFlash : true
        }));
        app.post('/login',  passport.authenticate('local-login', {
    
            successRedirect : '/profile',
            failureRedirect : '/login',
            failureFlash :true
    
        }));
    app.get('/logout',function(req,res){
        res.cookie('connect.sid', '', {expires: new Date(1), path: '/' });
       req.logOut();
        res.clearCookie('connect.sid', { path: '/' });
        res.redirect('/');
    });
    
    function isLoggedIn(req, res, next){
    
        if(req.isAuthenticated())
          return next();
    
        console.log("hiii");
        res.redirect('/');
    }
    

    };

    server.js

        var express = require('express');
    var app = express();
    var port = process.env.PORT || 3000;
    var mongoose = require('mongoose');
    var passport = require('passport');
    var flash=require('connect-flash');
    var morgan=require('morgan');
    var bodyParser = require('body-parser');
    var cookieParser=require('cookie-parser');
    //
    var session=require('express-session');
    var RedisStore = require('connect-redis')(session);
    var redis   = require("redis");
    var redis_client  = redis.createClient();
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({extended: true}));
    var configDb=require('./config/database.js');
    mongoose.connect(configDb.url);
    
    require('./config/passport')(passport);
    
    app.use(morgan('dev'));
    app.use(cookieParser());
    app.use(bodyParser());
    app.set('view engine', 'ejs');
    
    
    app.use(session({
        store: new RedisStore({
        host: '127.0.0.1',
        port: 6379,
        client: redis_client
    }),
        secret : 'foo',
        resave: false,
        saveUninitialized: false
    }));
    app.use(function (req, res, next) {
        if (!req.session) {
            return next(new Error('oh no')); // handle error
        }
        next();
    });
    
    
    });
    
    app.use(passport.initialize());
    app.use(passport.session());
    app.use(flash());
    
    require('./app/routes')(app, passport, session);
    app.listen(port, function(){
        console.log('server is at port' + port);
    });