Chapter 5 of 8
Course Progress0 of 8 completed (0%)

Cybersecurity Essentials for Developers · Chapter 5 · ~15 min · Intermediate

XSS, CSRF & Safe Browsers

Master client-side web application security. Understand Stored, Reflected, and DOM-based Cross-Site Scripting (XSS), learn how Cross-Site Request Forgery (CSRF) abuses ambient browser credentials, and deploy modern browser defenses like Content Security Policy (CSP) and SameSite cookies.

  • Distinguish the three primary types of XSS: Stored, Reflected, and DOM-based
  • Understand how CSRF exploits ambient browser authentication credentials
  • Configure modern browser defenses: CSP (Content-Security-Policy) & SameSite cookies
  • Simulate XSS payload sanitization and DOM sink execution in an interactive visualizer

XSS, CSRF & Safe Browsers: learn it visually

Master client-side web application security. Understand Stored, Reflected, and DOM-based Cross-Site Scripting (XSS), learn how Cross-Site Request Forgery (CSRF) abuses ambient browser credentials, and deploy modern browser defenses like Content Security Policy (CSP) and SameSite cookies.

XSS, CSRF & Safe BrowsersMaster client-side web application security. Understand Stored, Reflected, and DOM-based Cross-Site Scripting (XSS), learn how Cross-Site Request Forgery (CSRF) abuses ambient browser credentials, and deploy modern browser defenses like Content Security Policy (CSP) and SameSite cookies.UNDERSTANDXSSFOLLOW THE FLOWCSRFAPPLY ITSafe BrowsersXSS, CSRF & Safe BrowsersMaster client-side web application security. Understand Stored, Reflected, and DOM-based Cross-Site Scripting (XSS), learn how Cross-Site Request Forgery (CSRF) abuses ambient browser credentials, and deploy modern browser defenses like Content Security Policy (CSP) and SameSite cookies.UNDERSTANDXSSFOLLOW THE FLOWCSRFAPPLY ITSafe Browsers

1Everyday Intuition: The Poisoned Billboard vs The Forged Check

To master web client security, you must clearly distinguish between XSS and CSRF:

XSS (Cross-Site Scripting): The Poisoned Billboard

An attacker posts a malicious notice on your app's public community billboard. When innocent visitors read the billboard, the invisible hypnotic ink causes their eyes (their browser) to execute the attacker's rogue commands — stealing their passwords and secret session tokens.

CSRF (Cross-Site Request Forgery): The Forged Bank Slip

You are logged into your online bank. In another browser tab, you visit a malicious site. That site quietly submits a hidden form to bank.com/transfer?amount=$1000. Because your browser automatically includes your bank session cookie with every request to bank.com, the bank executes the transfer believing you sent it!

Concept Check

What is the fundamental difference between Cross-Site Scripting (XSS) and Cross-Site Request Forgery (CSRF)?

2Architecture & Code Mechanics: Modern Browser Shields

Modern browsers provide robust built-in security features to combat XSS and CSRF:

Wrong idea: Direct innerHTML Injection of Untrusted User Text

element.innerHTML = userBio → Executes Attacker JavaScript in Victim SessionBrowser parses injected <script> or <img onerror> tags immediately

Setting user-submitted profile bios or comments with `element.innerHTML = comment` or React's `dangerouslySetInnerHTML` without rigorous HTML sanitization.

Real system: Safe Text Nodes & DOMPurify Sanitization

element.textContent = bio → Rendered as Harmless Literal TextHTML tags are treated as raw visible text characters, neutralizing execution

Rely on safe text setters (`element.textContent = bio`) or standard React JSX interpolation `{bio}`, which automatically encodes HTML entities (`&lt;`, `&gt;`, `&amp;`).

Production Express Helmet & SameSite Cookie Configuration

Below is how modern production backends configure HTTP response headers with Helmet and protect cookies against both XSS theft and CSRF:

import express from "express";
import helmet from "helmet";

const app = express();

// 1. Strict Content Security Policy (CSP) with cryptographic nonces
app.use(
  helmet.contentSecurityPolicy({
    directives: {
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'", (req, res) => `'nonce-${res.locals.cspNonce}'`],
      objectSrc: ["'none'"],
      upgradeInsecureRequests: [],
    },
  })
);

// 2. Cookie Hardening against XSS and CSRF
app.post("/api/login", (req, res) => {
  const sessionToken = createSession();

  res.cookie("auth_session", sessionToken, {
    httpOnly: true,  // JavaScript CANNOT read this cookie (neutralizes XSS theft!)
    secure: true,    // Transmitted ONLY over HTTPS
    sameSite: "lax", // Browser will NOT send cookie on cross-site POSTs (neutralizes CSRF!)
    maxAge: 86400000,
  });

  res.json({ ok: true });
});
Concept Check

How does setting 'SameSite=Lax' or 'SameSite=Strict' on an authentication cookie block CSRF attacks?

3Interactive Visual Simulation: Browser DOM & XSS Defense Simulator

Simulate how an injected script payload interacts with the browser DOM, Cookie Storage, and external Command-and-Control (C2) servers. Toggle different defenses to see how layered protection works:

Interactive Browser DOM & XSS Defense Simulator

BREACH: TOKEN EXFILTRATED
https://app.codershub.com/dashboardDOM ParserinnerHTML (Vulnerable)SCRIPT EXECUTED!Injected JS running in DOMCookie Storage JarHttpOnly: NO (Readable)session_token LEAKEDdocument.cookie accessedAttacker C2 (evil.c2)Listening for ExfiltrationsSTOLEN TOKEN CAPTURED!
Current Browser Defense Evaluation:

Critical Vulnerability: Malicious JavaScript executed in the user's browser, read the non-HttpOnly cookie via document.cookie, and exfiltrated the session token to evil.c2. Enable HttpOnly, DOMPurify, or CSP to stop this attack!

Concept Check

Which of the following JavaScript DOM methods is considered a dangerous XSS sink that should be avoided with untrusted input?

4Hands-On Challenge: Secure Client Rendering & Cookie Handlers

A newly shipped microservice was flagged by an internal security scan for storing un-sanitized user bios in raw HTML and setting cookies with httpOnly: false. Harden the code below and run verification:

Express & React Hardening · Fix XSS Sinks & Cookie Security
JavaScript

🎯 Find and fix the bugs in the code above, then press Run & verify to test your solution.

Need a hint?
  • Prevent JavaScript cookie theft: set httpOnly: true inside res.cookie options.
  • Prevent CSRF and unencrypted transport: set secure: true and sameSite: "strict" (or "lax").
  • Remove the dangerous XSS sink: eliminate dangerouslySetInnerHTML or wrap input with DOMPurify.sanitize(userBio).

5Architecture Recap & Next Steps

  • Context-Aware Encoding: Never pass raw user strings into HTML sinks like innerHTML; use safe text setters (textContent) or DOMPurify.
  • HttpOnly Cookies: Mark all authentication cookies HttpOnly so that even if an attacker discovers an XSS bug, they cannot steal session tokens via document.cookie.
  • SameSite Protection: Use SameSite=Lax or SameSite=Strict to ensure cookies are never attached to malicious cross-site requests.
  • Content Security Policy: Enforce strict CSP with cryptographic nonces to block rogue inline script execution at the browser engine level.

Ready for Chapter 6? Mark this chapter as complete to proceed to Passwords & JWT Tokens:

Enjoying this free lesson? Your support helps us build more free animated chapters.

Support Us