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?