JAVASCRIPT

Secure Cookie Configuration for Express.js Applications

Configure HTTP-only, secure, and SameSite attributes for cookies in Express.js to enhance application security and mitigate risks like XSS and CSRF.

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

const app = express();

app.use(cookieParser());

// Example 1: Setting a secure session cookie (commonly done via express-session, but shown explicitly)
app.get('/login-and-set-cookie', (req, res) => {
  const userSessionId = 'some_unique_session_id_for_user_123'; // In a real app, this comes from authentication

  // Set a secure, HTTP-only, and SameSite=Lax cookie
  res.cookie('sessionId', userSessionId, {
    maxAge: 3600000, // 1 hour expiration in milliseconds
    httpOnly: true,  // Prevents client-side JavaScript access
    secure: process.env.NODE_ENV === 'production', // Send only over HTTPS in production
    sameSite: 'Lax', // Protects against some CSRF attacks
    // domain: '.example.com', // Optional: if subdomains need to access the cookie
    // path: '/dashboard' // Optional: if cookie should only be sent for specific paths
  });

  res.send('Login successful! Session cookie set.');
});

// Example 2: Reading a cookie
app.get('/read-cookie', (req, res) => {
  const sessionId = req.cookies.sessionId;
  if (sessionId) {
    res.send(`Session ID from cookie: ${sessionId}`);
  } else {
    res.send('No session ID cookie found.');
  }
});

// Example 3: Clearing a cookie
app.get('/logout-and-clear-cookie', (req, res) => {
  res.clearCookie('sessionId', {
    httpOnly: true, // Ensure these match the original cookie's attributes
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'Lax'
  });
  res.send('Logout successful! Session cookie cleared.');
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
How it works: This Express.js snippet illustrates how to properly configure cookies with essential security attributes: `HttpOnly`, `Secure`, and `SameSite`. `HttpOnly` prevents client-side JavaScript from accessing the cookie, mitigating XSS risks. `Secure` ensures the cookie is only sent over HTTPS connections, protecting against eavesdropping. `SameSite` helps prevent CSRF attacks by controlling when cookies are sent with cross-site requests. Setting these attributes is crucial for safeguarding sensitive information like session IDs stored in cookies.

Need help integrating this into your project?

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

Hire DigitalCodeLabs