Web SecurityWeb Security · Lesson 04

Cross-Site Scripting (XSS)

Reflected, stored and DOM XSS - impact and prevention.

Video tutorialTrack course · freeCodeCamp
Speed
Next lesson
Watch 00:00 · 2 checkpoints Watch on YouTube More on this topic
Transcript & captions
11/11

XSS happens when attacker-controlled input is rendered as code in another user's browser. The attacker's script then runs with the victim's session: it can read the DOM, call the API as them, or steal tokens.

TypeWhere the payload lives
ReflectedIn the request, echoed straight back in the response
StoredSaved in the database, served to every viewer
DOM-basedNever touches the server - unsafe client-side JS sinks
Vulnerable sink vs safe sinkjs
// VULNERABLE - raw HTML from user input
el.innerHTML = params.get('q');

// SAFE - text only, never parsed as HTML
el.textContent = params.get('q');
See escaping in action (safe demo)
  • Escape on output, contextually (HTML, attribute, URL, JS).
  • Prefer textContent and framework binding over innerHTML.
  • Sanitise rich HTML with a vetted library such as DOMPurify.
  • Add a strict Content-Security-Policy as defence in depth.
  • Set HttpOnly on session cookies so script cannot read them.

Knowledge check

0/2 answered

Stored XSS is more severe than reflected because...

Which is the safe sink?