JAVASCRIPT

Configure Secure and HttpOnly Session Cookies in Express.js

Learn to enhance web application security by properly configuring HttpOnly, Secure, and SameSite attributes for session cookies in Node.js Express applications.

const express = require('express');
const session = require('express-session');
const helmet = require('helmet'); // Optional, but recommended for other security headers
require('dotenv').config(); // For process.env.SESSION_SECRET

const app = express();

// Use helmet for general security best practices (optional, but good)
app.use(helmet());

// Configure express-session middleware
app.use(session({
    secret: process.env.SESSION_SECRET, // A strong, randomly generated string. NEVER hardcode in production.
    name: 'sessionId', // Custom name for the session cookie to obscure its purpose
    resave: false, // Don't save session if unmodified
    saveUninitialized: false, // Don't create session until something is 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
        sameSite: 'Lax', // Protects against some CSRF attacks. Options: 'Strict', 'Lax', 'None'
        maxAge: 1000 * 60 * 60 * 24, // 24 hours in milliseconds (cookie expiration)
        domain: process.env.COOKIE_DOMAIN || undefined // Specify your domain (e.g., 'yourdomain.com')
    }
}));

// Example route
app.get('/', (req, res) => {
    if (req.session.views) {
        req.session.views++;
        res.send(`Views: ${req.session.views}. Session ID: ${req.sessionID}`);
    } else {
        req.session.views = 1;
        res.send('Welcome to your first visit!');
    }
});

app.listen(3000, () => {
    console.log('Server running on port 3000');
    console.log('Ensure you have a .env file with SESSION_SECRET=YOUR_VERY_STRONG_RANDOM_SECRET');
});
How it works: Properly configuring session cookies is fundamental for web application security. This Node.js Express snippet shows how to set crucial cookie attributes using the `express-session` middleware. `httpOnly: true` prevents client-side JavaScript from accessing the cookie, mitigating XSS attacks that try to steal session tokens. `secure: true` ensures the cookie is only sent over HTTPS, protecting against interception. `sameSite: 'Lax'` (or 'Strict') helps prevent Cross-Site Request Forgery (CSRF) by restricting when browsers send cookies with cross-site requests. Using a strong `secret` from environment variables is vital for session integrity. These configurations significantly reduce the risk of session hijacking and other cookie-related attacks.

Need help integrating this into your project?

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

Hire DigitalCodeLabs