JAVASCRIPT

Configuring Secure HTTPOnly and SameSite Cookies in Node.js

Enhance session security in your Express.js application by properly setting 'Secure', 'HTTPOnly', and 'SameSite' attributes for cookies to prevent XSS and CSRF attacks.

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

app.use(session({
  secret: 'your_super_secret_key_here', // Replace with a long, random string
  resave: false,
  saveUninitialized: false, // Don't save sessions that are new but not modified
  cookie: {
    httpOnly: true, // Prevents client-side JavaScript from accessing the cookie
    secure: process.env.NODE_ENV === 'production', // Ensure cookies are only sent over HTTPS in production
    maxAge: 1000 * 60 * 60 * 24, // 24 hours (in milliseconds)
    sameSite: 'Lax', // Protects against CSRF attacks. Options: 'Strict', 'Lax', 'None'
  }
}));

app.get('/', (req, res) => {
  if (req.session.views) {
    req.session.views++;
    res.send(`You visited this page ${req.session.views} times.`);
  } else {
    req.session.views = 1;
    res.send('Welcome to your first visit!');
  }
});

app.get('/logout', (req, res) => {
  req.session.destroy(err => {
    if (err) {
      return res.status(500).send('Could not log out, please try again.');
    }
    res.clearCookie('connect.sid'); // Or whatever your session cookie name is
    res.send('Logged out successfully.');
  });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
How it works: Proper cookie configuration is crucial for web security. This Node.js Express snippet demonstrates how to set `httpOnly`, `secure`, and `sameSite` flags for session cookies using `express-session`. `httpOnly: true` prevents client-side JavaScript from accessing the cookie, mitigating XSS attacks. `secure: true` ensures the cookie is only sent over HTTPS, protecting it from interception. `sameSite: 'Lax'` (or 'Strict') helps prevent Cross-Site Request Forgery (CSRF) by restricting when browsers send cookies with cross-site requests. These attributes significantly enhance the security of user sessions.

Need help integrating this into your project?

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

Hire DigitalCodeLabs