JAVASCRIPT

Secure Cookie Handling in Express.js

Learn how to secure session cookies in Express.js applications by properly configuring HttpOnly, Secure, and SameSite flags to mitigate common web vulnerabilities like XSS and CSRF.

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

// Configure secure session cookie options
app.use((req, res, next) => {
  res.cookie('session_id', 'some_secure_session_token', {
    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. Options: 'Strict', 'Lax', 'None'
    maxAge: 3600000, // Cookie expiry time in milliseconds (1 hour)
    path: '/' // Path for which the cookie is valid
  });
  next();
});

app.get('/', (req, res) => {
  res.send('Cookie set securely!');
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
How it works: This Express.js snippet demonstrates how to set secure cookie options. The `httpOnly` flag prevents client-side scripts from accessing the cookie, thwarting XSS attacks that try to steal session tokens. The `secure` flag ensures the cookie is only sent over HTTPS, crucial for protecting data in transit (only set in production). The `sameSite` flag helps mitigate CSRF attacks by controlling when cookies are sent with cross-site requests. 'Lax' is often a good balance for user experience and security, but 'Strict' offers stronger protection if compatible with application flow. `maxAge` and `path` define the cookie's lifespan and scope.

Need help integrating this into your project?

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

Hire DigitalCodeLabs