← Back to all snippets
JAVASCRIPT

Configuring Secure and HttpOnly Cookies in Node.js Express

Ensure session cookies are secure and protected from client-side script access by setting HttpOnly, Secure, and SameSite attributes in your Node.js Express application.

const express = require('express');
const session = require('express-session');

const app = express();

app.use(session({
  secret: process.env.SESSION_SECRET || 'your_super_secret_key',
  resave: false,
  saveUninitialized: false,
  cookie: {
    httpOnly: true, // Prevent client-side script access
    secure: process.env.NODE_ENV === 'production', // Send cookie only over HTTPS
    sameSite: 'Lax', // Protect against CSRF attacks
    maxAge: 1000 * 60 * 60 * 24 // 24 hours
  }
}));

app.get('/', (req, res) => {
  if (!req.session.views) {
    req.session.views = 0;
  }
  req.session.views++;
  res.send(`Views: ${req.session.views}`);
});

app.listen(3000, () => console.log('Server running on port 3000'));
How it works: This Node.js Express snippet demonstrates how to configure session cookies with critical security attributes. `httpOnly: true` prevents client-side JavaScript from accessing the cookie, mitigating XSS risks. `secure: true` ensures the cookie is only sent over HTTPS connections, protecting against eavesdropping. `sameSite: 'Lax'` helps prevent Cross-Site Request Forgery (CSRF) by restricting cookie delivery for cross-site requests.

Need help integrating this into your project?

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

Hire DigitalCodeLabs