JAVASCRIPT

Set Secure HTTP-Only Cookies with Node.js Express

Learn to securely set cookies in Node.js Express applications, using HttpOnly, Secure, and SameSite attributes to protect against XSS and CSRF attacks.

const express = require('express');
const app = express();

app.get('/login', (req, res) => {
    // In a real application, authenticate user first
    const userId = 'user123'; 
    
    res.cookie('sessionToken', 'someSecureRandomTokenHere',
        {
            httpOnly: true,  // Prevents client-side JavaScript access
            secure: true,    // Ensures cookie is sent only over HTTPS
            sameSite: 'Lax', // Protects against some CSRF attacks
            maxAge: 3600000, // Cookie expires in 1 hour (in milliseconds)
            path: '/'        // Cookie is valid for all paths
        }
    );
    res.send('Logged in and cookie set securely!');
});

app.listen(3000, () => {
    console.log('Server running on port 3000');
});
How it works: This Node.js Express snippet demonstrates how to set a secure cookie. The `httpOnly: true` attribute prevents client-side JavaScript from accessing the cookie, protecting against XSS. `secure: true` ensures the cookie is only sent over HTTPS connections, safeguarding against man-in-the-middle attacks. `sameSite: 'Lax'` helps mitigate certain types of Cross-Site Request Forgery (CSRF) attacks by controlling when the browser sends the cookie with cross-origin requests. `maxAge` defines the cookie's expiration, and `path` specifies its scope within the domain.

Need help integrating this into your project?

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

Hire DigitalCodeLabs