JAVASCRIPT

Set Secure Cookie Flags (HttpOnly, Secure, SameSite) in Express

Improve web application security by correctly configuring HTTP cookie flags like HttpOnly, Secure, and SameSite in your Node.js Express server to protect against common attacks.

const express = require('express');
const cookieParser = require('cookie-parser');
const session = require('express-session'); // For session management

const app = express();

app.use(cookieParser());
app.use(session({
  secret: 'your_strong_secret_key_here', // Used to sign the session ID cookie
  resave: false, // Don't save session if unmodified
  saveUninitialized: false, // Don't create session until something stored
  cookie: {
    httpOnly: true, // Prevents client-side JavaScript from accessing the cookie
    secure: process.env.NODE_ENV === 'production', // Ensures cookie is sent only over HTTPS
    sameSite: 'Lax', // Protects against CSRF attacks. Can be 'Strict', 'Lax', or 'None'
    maxAge: 1000 * 60 * 60 * 24 * 7 // 1 week
  }
}));

app.get('/', (req, res) => {
  // Set a session value
  if (req.session.views) {
    req.session.views++;
  } else {
    req.session.views = 1;
  }
  res.send(`You have visited this page ${req.session.views} times. Session ID: ${req.session.id}`);
});

app.get('/set-custom-cookie', (req, res) => {
  res.cookie('custom_data', 'some_value', {
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'Lax',
    maxAge: 1000 * 60 * 5 // 5 minutes
  });
  res.send('Custom secure cookie set!');
});


const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
How it works: This snippet demonstrates how to set crucial security flags for HTTP cookies in an Express.js application, typically for session cookies or other sensitive data. `httpOnly: true` prevents client-side JavaScript from accessing the cookie, mitigating XSS attacks. `secure: true` ensures the cookie is only sent over HTTPS connections, protecting against man-in-the-middle attacks. `sameSite: 'Lax'` (or `'Strict'`) protects against Cross-Site Request Forgery (CSRF) attacks by restricting when the browser sends cookies with cross-site requests. These flags significantly enhance the security posture of your application's cookie management.

Need help integrating this into your project?

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

Hire DigitalCodeLabs