← Back to all snippets
JAVASCRIPT

Configure Secure Session Cookies in Express.js

Strengthen your Express.js application's session management by properly configuring `HttpOnly`, `Secure`, and `SameSite` flags for all cookies to prevent common attacks.

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

const app = express();

// Secret should be a strong, randomly generated string, stored securely
// For production, use environment variables (e.g., process.env.SESSION_SECRET)
const SESSION_SECRET = 'your_strong_secret_key_here_at_least_32_chars'; 

app.use(cookieParser(SESSION_SECRET)); // Use cookie-parser before session middleware if needed

app.use(session({
  secret: SESSION_SECRET,
  resave: false, // Don't save session if unmodified
  saveUninitialized: false, // Don't create session until something stored
  cookie: {
    httpOnly: true, // Prevents client-side JavaScript from accessing the cookie
    secure: process.env.NODE_ENV === 'production', // Send cookie only over HTTPS in production
    maxAge: 1000 * 60 * 60 * 24, // 24 hours (in milliseconds)
    sameSite: 'Lax', // Protects against CSRF attacks. 'Strict' is more secure but can impact user experience. 'None' requires 'Secure'.
  },
}));

app.get('/login', (req, res) => {
  req.session.userId = 'user123'; // Store user data in session
  res.send('Logged in and session created!');
});

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

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
How it works: This snippet demonstrates how to configure secure session cookies in an Express.js application using the `express-session` middleware. Key cookie options are set: `httpOnly: true` prevents client-side JavaScript access, `secure: true` ensures cookies are only sent over HTTPS (critical in production), and `sameSite: 'Lax'` helps mitigate Cross-Site Request Forgery (CSRF) attacks. Using a strong, securely stored `secret` is also vital for session integrity.

Need help integrating this into your project?

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

Hire DigitalCodeLabs