JAVASCRIPT

Configure Secure HttpOnly SameSite Cookies for Session Management

Enhance session security in your web application by properly configuring HttpOnly, Secure, and SameSite attributes for session cookies to mitigate various client-side attacks.

const express = require('express');
const session = require('express-session');
const cookieParser = require('cookie-parser');

const app = express();

app.use(cookieParser());

// Configure express-session middleware with secure options
app.use(session({
  secret: 'a_very_strong_and_long_random_secret_key_for_session_encryption', // MUST be a strong, unique secret
  resave: false, // Don't save session if unmodified
  saveUninitialized: false, // Don't create session until something stored
  name: 'sessionId', // Custom name for the session ID cookie
  cookie: {
    httpOnly: true, // Prevents client-side JavaScript from accessing the cookie
    secure: process.env.NODE_ENV === 'production', // Only send cookie over HTTPS in production
    maxAge: 3600000, // Session expiration time (1 hour in milliseconds)
    sameSite: 'Lax', // Protects against CSRF attacks, set to 'Strict' for stronger protection
  }
}));

app.get('/login', (req, res) => {
  // Simulate user login
  req.session.userId = 'user123';
  req.session.isAuthenticated = true;
  res.send('Logged in successfully! Session ID cookie set with secure flags.');
});

app.get('/dashboard', (req, res) => {
  if (req.session.isAuthenticated) {
    res.send(`Welcome to your secure dashboard, user ${req.session.userId}!`);
  } else {
    res.status(401).send('Unauthorized. Please log in.');
  }
});

app.listen(3000, () => {
  console.log('Server with secure sessions running on port 3000');
});
How it works: This snippet demonstrates configuring `express-session` with crucial security attributes for session cookies. `httpOnly: true` prevents client-side JavaScript from accessing the session cookie, mitigating XSS attacks. `secure: true` (activated in production) ensures the cookie is only sent over HTTPS. `maxAge` sets an expiration. `sameSite: 'Lax'` (or 'Strict') helps prevent CSRF attacks by restricting when the browser sends the cookie with cross-site requests. These settings collectively harden session management.

Need help integrating this into your project?

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

Hire DigitalCodeLabs