Cross-Site Scripting (XSS): Prevention in Modern Applications
Cross-Site Scripting (XSS) is a vulnerability where attackers inject malicious scripts into web pages viewed by other users. It is consistently in the OWASP Top 10 and can lead to session theft, credential harvesting, and malicious redirects.
Types of XSS
- Stored XSS: Malicious script is stored in the database and served to all users who view the affected page — the most severe type
- Reflected XSS: Malicious input is reflected in the immediate server response — requires tricking a user into clicking a crafted link
- DOM-based XSS: The attack payload is executed by client-side JavaScript that reads from the DOM without proper sanitisation
Prevention Techniques
- Output encoding: Encode all user-supplied data before rendering it in HTML — the primary defence. Modern frameworks (React, Vue, Angular) do this automatically by default.
- Content Security Policy (CSP): A response header that restricts which scripts can execute — limits the impact of XSS even when it occurs
- Input validation: Validate and reject input that does not conform to expected format — a secondary defence
- Avoid innerHTML: Do not use innerHTML or dangerouslySetInnerHTML with user-supplied data
- HttpOnly cookies: Prevents session cookie theft via XSS
Our Approach
We use frameworks and templating engines with automatic output encoding, implement strict Content Security Policies, and include XSS testing in our security QA process.