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 likeinnerHTML. The server is not involved at all.
Prevention:
- Escape output for its context. Frameworks like React do this by default.
- Avoid
innerHTMLand 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
HttpOnlycookies, 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
HttpOnlycookies add extra layers of defence.
Read more