JAVASCRIPT

Configuring Secure HTTP-Only Cookies with SameSite (Node.js)

Learn to set HTTP-Only, Secure, and SameSite attributes for cookies in Node.js Express to enhance security against XSS and CSRF attacks.

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

app.use(cookieParser());

app.get('/set-secure-cookie', (req, res) => {
  // Set a cookie with essential security flags
  res.cookie('session_token', 'random_secure_value_123',
    {
      httpOnly: true,     // Prevents client-side JavaScript access to the cookie
      secure: true,       // Ensures the cookie is only sent over HTTPS
      sameSite: 'Lax',    // Mitigates CSRF attacks; 'Strict' is even stronger but might impact user experience
      maxAge: 3600000,    // Cookie expiration in milliseconds (1 hour)
      // domain: '.example.com', // Uncomment and set your domain for cross-subdomain cookies
      // path: '/api/',      // Uncomment and set path if the cookie should only be sent for specific paths
    }
  );
  res.send('Secure cookie set!');
});

app.get('/read-cookie', (req, res) => {
  // Note: httpOnly cookies are not accessible by client-side JavaScript
  // They are automatically sent by the browser with requests to the server.
  // Server-side, you can access them via req.cookies
  const token = req.cookies.session_token;
  if (token) {
    res.send(`Session token (server-side): ${token}`);
  } else {
    res.send('No session token found.');
  }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
How it works: This Node.js Express snippet demonstrates how to configure cookies with critical security attributes: `httpOnly`, `secure`, and `sameSite`. Setting `httpOnly: true` prevents client-side JavaScript from accessing the cookie, largely mitigating XSS risks. `secure: true` ensures the cookie is only transmitted over HTTPS connections, protecting against eavesdropping. `sameSite: 'Lax'` (or 'Strict') helps prevent Cross-Site Request Forgery (CSRF) attacks by controlling when cookies are sent with cross-site requests. These attributes are crucial for hardening web application security.

Need help integrating this into your project?

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

Hire DigitalCodeLabs