JAVASCRIPT

Set Secure Cookie Attributes for Web Applications

Secure your web application's cookies in Express.js by implementing `HttpOnly`, `Secure`, and `SameSite` attributes, protecting against XSS, MITM, and CSRF attacks.

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

app.get('/login-success', (req, res) => {
  const token = 'your_jwt_or_session_token'; // Replace with actual token generation

  res.cookie('sessionToken', token, {
    httpOnly: true, // Prevents client-side JavaScript from accessing the cookie
    secure: true,   // Ensures cookie is only sent over HTTPS
    sameSite: 'Lax', // Protects against some CSRF attacks; 'Strict' is stronger but can break legitimate navigations
    maxAge: 3600000, // Cookie expires after 1 hour (in milliseconds)
    path: '/'       // Cookie is valid for all paths on the domain
  });

  res.send('Logged in successfully! Token set securely in cookie.');
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});
How it works: This Node.js (Express) snippet shows how to set secure attributes for HTTP cookies. `httpOnly: true` prevents client-side JavaScript from accessing the cookie, mitigating XSS risks. `secure: true` ensures the cookie is only sent over encrypted HTTPS connections, protecting against Man-in-the-Middle (MITM) attacks. `sameSite: 'Lax'` helps protect against Cross-Site Request Forgery (CSRF) by restricting when the browser sends the cookie with cross-site requests. Setting `maxAge` or `expires` is also important 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