Course contentsShow
← Node.js
Lesson 678 of 1,9807. Web Framework Architecture and MiddlewareFree lesson

Secure Cookie Management

Configure secure flags for sessions to mitigate cross-site scripting and request forgery.

Secure Cookie Management

In this lesson, you will learn how to harden your session cookies against common web attacks by applying specific security flags in your Node.js application.

When a user logs in, your server typically sends a Set-Cookie header to the browser. If left at default settings, that cookie is vulnerable to theft via Cross-Site Scripting (XSS) or exploitation via Cross-Site Request Forgery (CSRF). To secure these sessions, we use three primary flags: httpOnly, secure, and sameSite.

The Security Flags

  • httpOnly: true: This is your first line of defense against XSS. By setting this flag, you prevent client-side JavaScript from accessing the cookie via document.cookie. Even if an attacker injects a malicious script into your page, they cannot steal the session token.
  • secure: true: This ensures the cookie is only transmitted over encrypted HTTPS connections. Without this, a cookie could be intercepted in plain text over an insecure network (like public Wi-Fi).
  • sameSite: 'strict' or 'lax': This flag controls whether your browser sends cookies with cross-site requests. Setting this to strict or lax significantly mitigates CSRF, as it tells the browser not to attach the cookie when requests originate from external sites.

Implementation Example

If you are using a standard session middleware in Express, you configure these flags within the session options:

app.use(session({
  secret: 'your-super-secret-key',
  cookie: {
    httpOnly: true, // Prevents XSS access
    secure: true,   // Requires HTTPS
    sameSite: 'lax' // Mitigates CSRF
  }
}));

It is important to remember that secure: true requires your server to be running over HTTPS. If you are developing locally without SSL, you might need a conditional check to disable it in the development environment, though it must always be enabled in production. By explicitly defining these properties, you ensure that your session data remains isolated from unauthorized access and accidental cross-origin leakage.

Key Takeaway: Always enable httpOnly, secure, and sameSite flags on session cookies to create a robust barrier against XSS and CSRF attacks.