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.
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!
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
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
Rely on safe text setters (`element.textContent = bio`) or standard React JSX interpolation `{bio}`, which automatically encodes HTML entities (`<`, `>`, `&`).
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 });
});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
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!
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:
🎯 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: trueinsideres.cookieoptions. - Prevent CSRF and unencrypted transport: set
secure: trueandsameSite: "strict"(or"lax"). - Remove the dangerous XSS sink: eliminate
dangerouslySetInnerHTMLor wrap input withDOMPurify.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
HttpOnlyso that even if an attacker discovers an XSS bug, they cannot steal session tokens viadocument.cookie. - SameSite Protection: Use
SameSite=LaxorSameSite=Strictto 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: