← Back to all snippets
JAVASCRIPT

Configure Secure and HttpOnly Cookies for Session Management

Enhance web application security by setting essential HttpOnly, Secure, and SameSite flags on cookies to protect against XSS and CSRF attacks.

// Using Express.js for a typical Node.js web application
const express = require('express');
const app = express();
const cookieParser = require('cookie-parser');

app.use(cookieParser());

app.get('/set-secure-cookie', (req, res) => {
  // Example: Setting a session cookie
  res.cookie('session_token', 'your_secure_session_id_here', {
    httpOnly: true,        // Prevents client-side JavaScript from accessing the cookie
    secure: true,          // Ensures cookie is only sent over HTTPS
    sameSite: 'Lax',       // Mitigates CSRF attacks; 'Strict' is even stronger
    maxAge: 3600000,       // Cookie expires after 1 hour (in milliseconds)
    path: '/',             // Cookie is valid for all paths on the domain
    // domain: 'yourdomain.com' // Optional: Specify domain if different from request origin
  });
  res.send('Secure cookie set!');
});

app.get('/get-cookie', (req, res) => {
  // Accessing cookies (httpOnly cookies are not accessible via client-side JS)
  res.send(`Session token (server-side): ${req.cookies.session_token || 'Not found'}`);
});

// Start server
// app.listen(3000, () => {
//   console.log('Server running on port 3000');
// });
How it works: This Node.js (Express) snippet demonstrates how to configure secure cookies. The `httpOnly: true` flag prevents client-side JavaScript from accessing the cookie, significantly reducing the risk of session hijacking via XSS attacks. `secure: true` ensures the cookie is only sent over encrypted HTTPS connections, protecting against eavesdropping. The `sameSite: 'Lax'` flag helps mitigate Cross-Site Request Forgery (CSRF) attacks by controlling when cookies are sent with cross-site requests. Setting these flags is a critical security best practice for 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