JAVASCRIPT

Secure Session Management in Express.js

Secure user sessions in Express.js by properly configuring `express-session` with `secret`, `resave`, `saveUninitialized`, and `cookie` options for production environments.

const express = require('express');
const session = require('express-session');
const cookieParser = require('cookie-parser'); // Needed for session cookies

const app = express();
app.use(cookieParser());

// In production, use a persistent session store (e.g., connect-mongo, connect-redis)
// const MongoStore = require('connect-mongo');

app.use(session({
  secret: process.env.SESSION_SECRET || 'your_super_secret_key_here', // MUST be a strong, random string
  name: 'my.session.id', // Custom session cookie name to avoid default 'connect.sid'
  resave: false, // Don't save session if unmodified
  saveUninitialized: false, // Don't create session until something stored
  cookie: {
    httpOnly: true, // Prevent client-side JavaScript from accessing the cookie
    secure: process.env.NODE_ENV === 'production', // Only send cookie over HTTPS in production
    maxAge: 24 * 60 * 60 * 1000, // Session expiration time (e.g., 24 hours in milliseconds)
    sameSite: 'Lax', // Protects against CSRF attacks in some scenarios ('Strict' or 'Lax')
  },
  // store: MongoStore.create({ mongoUrl: process.env.DB_URL }) // Example: Use a persistent store for production
}));

// Middleware to track session visits (example)
app.use((req, res, next) => {
  if (req.session.views) {
    req.session.views++;
  } else {
    req.session.views = 1;
  }
  console.log(`Session ID: ${req.sessionID}, Views: ${req.session.views}`);
  next();
});

app.get('/', (req, res) => {
  res.send(`You have visited this page ${req.session.views} times. Session ID: ${req.sessionID}`);
});

app.get('/logout', (req, res) => {
  req.session.destroy(err => {
    if (err) {
      return res.status(500).send('Could not log out, please try again.');
    }
    res.clearCookie('my.session.id'); // Clear the custom session cookie
    res.send('Logged out successfully!');
  });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
  console.log('Access http://localhost:3000/ and refresh to see session count increase.');
});
How it works: This snippet demonstrates how to securely manage user sessions in an Express.js application using the `express-session` middleware. Key security configurations for the `cookie` object include `httpOnly: true` (prevents client-side script access), `secure: true` (ensures cookies are only sent over HTTPS in production), `maxAge` (sets cookie expiration), and `sameSite: 'Lax'` (mitigates CSRF). A strong, randomly generated `secret` is crucial for session integrity, and `resave: false`, `saveUninitialized: false` prevent unnecessary session creation and saving.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs