1

I have a NextJS client running on localhost:3001 and a Express/MongoDB server running on localhost:3000.

For authentication I'm using express-session with connect-mongo like so:

app.use(session({
    secret: 'jordan-peterson-is-a-fraud',
    resave: false,
    saveUninitialized: false,
    unset: 'destroy',
    cookie: {
        httpOnly: false
    },
    store: new MongoStore({ mongooseConnection: mongoose.connection })
}));

On login I set req.session.user = userID, which seems to work fine: it registers a new session record in the sessions table in my database, and sends a set-cookie header with the value connect.sid=<encrypted-session-ID> to the client which gets stored in a session cookie.

So far, so good.

But on logout it seems that calling req.session.destroy() has no effect whatsoever. The client sends a POST with credentials to /logout on the server:

fetch('http://localhost:3000/logout', {
    method: 'post',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
    mode: 'cors',
    credentials: 'include'
})

And the server does seem to receive a correct req object that includes:

{
    ...
    sessionID: '<encrypted-session-ID>',
    session: Session {
      cookie: {
        path: '/',
        _expires: null,
        originalMaxAge: null,
        httpOnly: false
      }
    }
    ...
}

The console also prints [Function: destroy] when I log req.session.destroy. But nothing happens when I call it. The database is unchanged - with the session record still there from the login.

router.all('/logout', async function(req, res){
    if (req.session) {
        req.session.destroy();
        return res.end();
    }
}

Anyone know what I'm doing wrong here?

o01
  • 5,191
  • 10
  • 44
  • 85
  • 1
    Show the code where you call the destroy function. Also see this https://stackoverflow.com/questions/5573256/how-to-end-a-session-in-expressjs – Molda Jun 29 '20 at 10:46
  • I've updated the question like you asked. – o01 Jun 29 '20 at 10:51
  • try `req.logout();` then do a redirect – Lawrence Cherone Jun 29 '20 at 11:08
  • @o01 Have you found a solution? I have an IDENTICAL problem. Nothing happens on `req.session.destroy();`. The database (PostgreSQL in my case) is unchanged. I've been trying for days now! – Rok Benko Feb 14 '23 at 18:19

2 Answers2

1

You can use delete req.session.user;

Jatin verma
  • 61
  • 10
  • This kind of worked. At least the `user` property was removed from the session record in the database. But the rest of the session record is still there? – o01 Jun 29 '20 at 10:55
  • Could you please check if delete req.session works. – Jatin verma Jun 29 '20 at 11:00
-1
req.session.destroy(req.sessionID)
Jurshsmith
  • 182
  • 2
  • 4