CodePark/ questions / Frontend security
START PRACTICINGPRACTICE
Frontend question · Browser & web performance › Frontend security

What is XSS? Explain stored, reflected and DOM-based XSS and how to prevent it.

XSS (cross-site scripting) is when an attacker gets their script to run in your page, in your users' browsers. The script can then access the page, any cookies that aren't HttpOnly, and the user's session.

The three types:

  • Stored XSS: malicious input is saved on the server, for example in a comment, and shown to other users.
  • Reflected XSS: input from the request, such as a query parameter, is echoed back in the response.
  • DOM-based XSS: client-side JavaScript takes data from a source like location.hash. It writes the data into a dangerous sink like innerHTML. The server is not involved at all.

Prevention:

  • Escape output for its context. Frameworks like React do this by default.
  • Avoid innerHTML and similar sinks. If you must render HTML, sanitise it with a library like DOMPurify.
  • Validate URLs to block javascript: links.
  • Add a Content Security Policy (CSP) as a second layer of defence.
  • Use HttpOnly cookies, so scripts can't read them.
  • In XSS, an attacker's script runs in your origin.
  • The three types are stored, reflected and DOM-based XSS.
  • Escape output for its context, and avoid innerHTML.
  • Sanitise any HTML you must render, for example with DOMPurify.
  • CSP and HttpOnly cookies add extra layers of defence.