← Back to all snippets
JAVASCRIPT

Set Secure and HttpOnly Cookies

Enhance web application security by setting HttpOnly, Secure, and SameSite attributes on cookies. Prevent XSS attacks and mitigate CSRF vulnerabilities effectively.

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

app.use(cookieParser());

app.get('/login', (req, res) => {
  // Simulate a successful login
  const userId = 'user123';
  const sessionToken = 'a_very_secure_and_random_session_token';

  // Setting a secure, HttpOnly, and SameSite cookie
  res.cookie('session_id', sessionToken, {
    httpOnly: true,  // Prevents client-side JavaScript from accessing the cookie
    secure: true,    // Ensures the cookie is only sent over HTTPS
    sameSite: 'Lax', // Mitigates CSRF attacks; 'Strict' is even stronger but can impact user experience
    maxAge: 3600000, // Cookie expiration in milliseconds (1 hour)
    path: '/',       // The path for which the cookie is valid
  });

  res.send(`User ${userId} logged in. Session cookie set.`);
});

app.get('/dashboard', (req, res) => {
  const sessionId = req.cookies.session_id;
  if (sessionId) {
    res.send(`Welcome to the dashboard! Your session ID is (server-only): ${sessionId}`);
  } else {
    res.status(401).send('Not authenticated.');
  }
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});
How it works: This snippet demonstrates how to set cookies with critical security attributes in Express.js. The `httpOnly: true` attribute prevents client-side JavaScript from accessing the cookie, effectively mitigating XSS attacks where an attacker might try to steal session cookies. The `secure: true` attribute ensures the cookie is only sent over encrypted HTTPS connections, protecting it from eavesdropping. Lastly, `sameSite: 'Lax'` (or 'Strict') helps prevent Cross-Site Request Forgery (CSRF) attacks by restricting when the browser sends cookies with cross-site requests. These attributes are fundamental for secure session management.

Need help integrating this into your project?

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

Hire DigitalCodeLabs