JAVASCRIPT

Setting Secure, HttpOnly, and SameSite Cookies in Node.js

Secure your web application's cookies by setting HttpOnly, Secure, and SameSite attributes in Node.js/Express to prevent common session hijacking vulnerabilities.

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

app.get('/login-success', (req, res) => {
  // After successful authentication
  res.cookie('sessionID', 'some_secure_session_token', {
    httpOnly: true,  // Prevents client-side JavaScript access
    secure: true,    // Ensures cookie is only sent over HTTPS
    sameSite: 'Lax', // Prevents CSRF attacks (Strict, Lax, None)
    maxAge: 3600000, // 1 hour expiration in milliseconds
    path: '/',       // Cookie is valid for all paths
  });
  res.send('Logged in successfully! Session cookie set.');
});

// Example usage: Start the server
// app.listen(3000, () => console.log('Server running on port 3000'));
How it works: This Node.js (Express) snippet demonstrates how to set a secure session cookie. The `httpOnly: true` attribute prevents client-side JavaScript from accessing the cookie, mitigating XSS attacks. `secure: true` ensures the cookie is only sent over encrypted HTTPS connections. `sameSite: 'Lax'` helps protect against Cross-Site Request Forgery (CSRF) by controlling when cookies are sent with cross-site requests. Setting `maxAge` provides an expiration, and `path` defines the cookie's scope.

Need help integrating this into your project?

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

Hire DigitalCodeLabs