Lukas' Notes

web security

Definition

XSS Sanitisation

XSS sanitisation neutralises a payload before it reaches a parser that would execute it. The safe layer to sanitise at is the one whose parser will actually interpret the string — context matters, so the server encodes when the context is clear (and templates default to safe output), while client-side sinks are sanitised in JavaScript where the browser’s own parser is the victim.

innerHTML Is a Dangerous Sink

innerHTML is a dangerous sink

element.innerHTML = s parses s as HTML and adds it to the DOM without sanitisation, so <script> and onerror= run. Prefer the HTML Sanitizer API when it is available:

// removes all script entities using the default sanitizer
element.setHTML(s);
// innerHTML = s   // executes everything; never do this with untrusted input

Client-Side Libraries and Standards

Client-side libraries and standards

  • DOMPurify provides cross-browser sanitization.
  • The HTML Sanitizer API (element.setHTML(...)) is the native standardised equivalent, available in Chrome and Firefox from March 2026 (Safari does not yet support it).

On the server, templating libraries with safe defaults escape variables by default. Sanitisation must take place on the side whose parser will interpret the input, or in a form that matches that parser’s context.