Script Valley
JWT & Session Auth: Deep Dive
Session-Based AuthenticationLesson 3.4

secure session logout and session destruction

session destroy vs session clear, req.session.destroy, clearing the session cookie, logout redirect, garbage collection, destroy callback error handling

Secure Session Logout

Session Logout Flow

Logout must do two things: destroy the server-side session record and expire the client-side cookie. Doing only one creates a dangling session or a useless but valid cookie.

app.post('/logout', (req, res) => {
  req.session.destroy((err) => {
    if (err) {
      console.error('Session destroy error:', err);
      return res.status(500).json({ error: 'Logout failed' });
    }

    // Clear the session cookie on the client
    res.clearCookie('connect.sid', {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'strict'
    });

    res.json({ success: true });
  });
});

req.session.destroy removes the session from the store (Redis or memory) and sets req.session to undefined. Without the res.clearCookie call, the browser still holds the old session ID cookie — it just points to a deleted session. The user appears logged out, but that stale cookie could cause confusing error states.

The cookie name passed to clearCookie must match the name set in the session config. The default for express-session is connect.sid. If you configured a custom name option, use that instead.

Always handle the destroy callback's error argument. Session store writes can fail, and a failed destroy is a security event worth logging.

Up next

session middleware for route protection in Express

Sign in to track progress