← Back to all snippets
JAVASCRIPT

Setting Secure, HTTPOnly, and SameSite Cookie Attributes

Learn to configure essential security attributes (Secure, HTTPOnly, SameSite) for cookies in Express.js to protect against XSS, CSRF, and session hijacking vulnerabilities.

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

app.use(cookieParser());

app.get('/set-secure-cookie', (req, res) => {
  // Set a session cookie with all recommended security attributes
  res.cookie('session_id', 'some_secret_session_token', {
    httpOnly: true, // Prevents client-side JavaScript access to the cookie
    secure: process.env.NODE_ENV === 'production', // Ensures cookie is only sent over HTTPS
    sameSite: 'Lax', // Protects against CSRF attacks. Can be 'Strict', 'Lax', or 'None'
    maxAge: 3600000, // Cookie expires in 1 hour (in milliseconds)
    path: '/' // Cookie is valid for all paths
  });
  res.send('Secure cookie set!');
});

app.get('/read-cookie', (req, res) => {
  // httpOnly cookies cannot be read by client-side JavaScript,
  // but can be accessed by the server.
  res.send(`Session ID (server-side): ${req.cookies.session_id || 'Not set or httpOnly'}`);
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
How it works: This snippet shows how to set cookies with `httpOnly`, `secure`, and `sameSite` attributes using Express.js. `httpOnly` prevents client-side JavaScript from accessing the cookie, mitigating XSS risks. `secure` ensures the cookie is only sent over HTTPS. `sameSite` provides protection against Cross-Site Request Forgery (CSRF) by controlling when cookies are sent with cross-site requests. These attributes are crucial for protecting sensitive session information.

Need help integrating this into your project?

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

Hire DigitalCodeLabs