JAVASCRIPT

Configuring Secure, HttpOnly, and SameSite Cookies for Express Sessions

Enhance web application security by properly configuring session cookies with `Secure`, `HttpOnly`, and `SameSite` attributes in Node.js Express.

const express = require('express');
const session = require('express-session');
const helmet = require('helmet'); // For general security headers

const app = express();

// Apply Helmet for various security headers, including default CSP, X-XSS-Protection etc.
app.use(helmet());

// Configure express-session with secure cookie settings
app.use(session({
    secret: process.env.SESSION_SECRET || 'a_very_secret_key_that_should_be_in_env_variables',
    resave: false,
    saveUninitialized: false,
    name: 'sessionId', // Customize cookie name for security by obscurity
    cookie: {
        httpOnly: true, // Prevents client-side JavaScript from accessing the cookie
        secure: process.env.NODE_ENV === 'production', // Ensures cookie is sent only over HTTPS
        maxAge: 1000 * 60 * 60 * 24, // 24 hours in milliseconds
        sameSite: 'Lax', // Protects against CSRF attacks. 'Strict' is more secure but can break some UX.
                         // 'None' requires 'secure: true' and is used for cross-site requests (e.g., APIs)
    }
}));

// Example route
app.get('/', (req, res) => {
    if (req.session.views) {
        req.session.views++;
        res.send(`You have visited this page ${req.session.views} times.`);
    } else {
        req.session.views = 1;
        res.send('Welcome! This is your first visit.');
    }
});

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
    console.log(`Using session secret: ${process.env.SESSION_SECRET ? 'FROM_ENV' : 'DEFAULT'}`);
    console.log(`Cookie secure setting: ${process.env.NODE_ENV === 'production' ? 'true (HTTPS only)' : 'false (HTTP allowed)'}`);
});
How it works: This Node.js Express snippet demonstrates how to configure session cookies securely. The `httpOnly` attribute prevents client-side JavaScript from accessing the cookie, mitigating XSS attacks that try to steal session identifiers. The `secure` attribute ensures the cookie is only sent over HTTPS, protecting against eavesdropping. The `sameSite` attribute protects against CSRF (Cross-Site Request Forgery) by controlling when cookies are sent with cross-site requests; 'Lax' is a good balance for general web apps, while 'Strict' is more secure but might restrict some legitimate cross-site linking. A strong, securely managed `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