JAVASCRIPT

Enforce Secure Cookie Attributes in Node.js Express

Learn to set essential security attributes like `HttpOnly`, `Secure`, and `SameSite` on cookies in Node.js Express to protect against XSS and CSRF.

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

const app = express();
app.use(cookieParser());

// Example of setting a secure session cookie
app.get('/set-session-cookie', (req, res) => {
  res.cookie('session_id', 'some_secure_session_token_123',
    {
      httpOnly: true, // Prevents client-side JavaScript access
      secure: true,   // Ensures cookie is only sent over HTTPS
      sameSite: 'Lax', // Protects against CSRF attacks
      maxAge: 3600000, // 1 hour expiration
      path: '/',      // Cookie valid for all paths
    }
  );
  res.send('Session cookie set securely!');
});

// Example of setting another secure cookie with different SameSite policy
app.get('/set-preference-cookie', (req, res) => {
  res.cookie('user_pref', 'dark_theme',
    {
      httpOnly: false, // Can be accessed by client-side JS if needed
      secure: true,
      sameSite: 'Strict', // Stronger CSRF protection (less compatible)
      maxAge: 86400000, // 24 hours
    }
  );
  res.send('User preference cookie set securely!');
});

// Example of reading cookies
app.get('/read-cookies', (req, res) => {
  console.log('Cookies:', req.cookies);
  res.send(`Cookies: ${JSON.stringify(req.cookies)}`);
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
How it works: Properly configured cookie attributes are vital for web security. This Node.js Express snippet demonstrates how to set `HttpOnly`, `Secure`, and `SameSite` flags on cookies. `HttpOnly: true` prevents client-side JavaScript from accessing the cookie, mitigating XSS risks. `Secure: true` ensures the cookie is only sent over HTTPS, preventing interception. `SameSite` protects against Cross-Site Request Forgery (CSRF) attacks: `Lax` provides a good balance of security and compatibility, while `Strict` offers stronger protection by restricting cross-site requests more aggressively.

Need help integrating this into your project?

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

Hire DigitalCodeLabs