Nexus Void Research
XSS, Cross-Site Scripting, CWE-79, React, Angular, Vue, DOMPurify, Content Security Policy, How-to
How to Prevent XSS in JavaScript, React and Angular
How to prevent XSS: context-aware encoding, framework escape hatches to avoid, DOMPurify for user HTML, safe URLs and a nonce-based CSP.
To prevent XSS (cross-site scripting), encode untrusted data for the context it is written into, let your framework do that automatically, and avoid the APIs that bypass it (innerHTML, dangerouslySetInnerHTML, Angular's bypassSecurityTrust*, v-html). When you must render user HTML, sanitise it with a vetted library such as DOMPurify. Add a strict Content Security Policy and HttpOnly cookies so a missed bug does less damage.
Cross-site scripting lets an attacker run their JavaScript in another user's browser, inside your site. From there it can read the page, act as the user, steal tokens stored in JavaScript-readable storage and show fake login forms. MITRE tracks it as CWE-79, and it is still being exploited: CISA's Known Exploited Vulnerabilities catalog lists 33 XSS CVEs, 4 of them added in 2026, per our 2026 vulnerability statistics. The OWASP XSS Prevention Cheat Sheet is the reference; this guide turns it into steps for JavaScript, React, Angular, Vue and server-side templates.
What are the types of XSS?
Type | How it works | Example |
|---|---|---|
Stored XSS | Payload is saved (comment, profile, ticket) and served to every viewer |
|
Reflected XSS | Payload is in the request and echoed straight back |
|
DOM-based XSS | Client-side JavaScript writes untrusted data into the page |
|
All three have the same root cause: untrusted data ends up interpreted as HTML or JavaScript.
Step 1: Encode output for the right context
Encoding turns characters with special meaning into harmless text. The catch is that the right encoding depends on where the data lands:
Where the data goes | What to do |
|---|---|
HTML body text | HTML-encode |
HTML attribute value (quoted) | Attribute-encode, and always quote attributes |
URL in | Validate the scheme is |
Inside a | Avoid it. Pass data via a JSON data attribute or a |
CSS | Avoid putting user data in styles; if needed, allow-list values |
Most XSS bugs come from encoding for the wrong context, such as HTML-encoding a value placed in a javascript: URL or an event handler.
Step 2: Let your framework encode for you
Modern frameworks encode by default when you use their normal binding syntax:
React escapes values in JSX (
<p>{comment}</p>).Angular escapes interpolation (
{{ comment }}) and sanitises values bound to[innerHTML].Vue escapes mustache syntax (
{{ comment }}).Server templates such as Jinja2, Django templates, Twig, ERB, Razor and Thymeleaf auto-escape by default.
XSS in these frameworks almost always comes from the escape hatches. Search your codebase for them:
Framework | Escape hatch to review |
|---|---|
Plain JavaScript |
|
React |
|
Angular |
|
Vue |
|
Jinja2 / Django | ` |
Server-side generally | Building HTML strings by concatenation |
Step 3: Use safe DOM APIs in plain JavaScript
When writing to the page directly, use APIs that treat data as text:
For DOM-based XSS, treat location, document.referrer, postMessage data, localStorage and URL fragments as untrusted, exactly like request input on the server.
Step 4: Sanitise when you must render user HTML
Rich-text comments, markdown previews and CMS content sometimes need real HTML. Encoding would break them, so sanitise instead, with a maintained library, never with your own regular expressions:
In React:
On the server, use a sanitiser for your language, such as nh3 or bleach in Python, sanitize-html in Node.js, or the OWASP Java HTML Sanitizer. Keep the sanitiser updated, because bypasses are found and fixed over time.
Step 5: Validate URLs before putting them in links
Frameworks escape text, but they do not stop javascript: URLs in links:
Parse the URL and allow only https: and http::
Step 6: Add a Content Security Policy
A Content Security Policy (CSP) tells the browser which scripts may run, so an injected script is blocked even if encoding fails. A strict, nonce-based policy is the strongest common setup:
Generate a new random nonce per response and add it to your own <script> tags. Avoid 'unsafe-inline' and 'unsafe-eval', which undo most of the protection. Roll out with Content-Security-Policy-Report-Only first to find breakage.
Step 7: Limit what a successful XSS can steal
HttpOnly cookies for sessions, so scripts cannot read them, plus
SecureandSameSite.Avoid storing tokens in
localStorage, which any script on the page can read.Re-authenticate for sensitive actions such as changing email, password or payment details.
XSS prevention checklist
Check | Done when |
|---|---|
Framework auto-escaping on | No templates with autoescape disabled |
Escape hatches reviewed | Every |
User HTML sanitised | DOMPurify or a server-side sanitiser, kept updated |
URLs validated | Only http(s) in |
No data in script blocks | Data passed as JSON, not inline JavaScript |
CSP deployed | Nonce-based |
Cookies hardened | Session cookies HttpOnly, Secure, SameSite |
Add the escape-hatch search to your security code review, and see how to prevent SQL injection for the server-side equivalent.
How does ARGUS find XSS?
Rule-based static analysis flags dangerous sinks such as
innerHTML,dangerouslySetInnerHTML,v-html,bypassSecurityTrust*and disabled template escaping, with a suggested fix.AI taint analysis follows untrusted input to those sinks across files in Python, JavaScript, TypeScript, Ruby, Go, Java and PHP, and shows the path as a file-by-file timeline, which separates a real injection from a sink that only ever receives constants.
Every AI finding is independently challenged and dropped if it cannot be substantiated.
Pull request review comments inline on new sinks in changed lines and requests changes for Critical and High findings.
Fix pull requests: Assign to Agent applies the fix, such as switching to
textContentor adding sanitisation, verifies it with a build and a re-scan, and opens a pull request for you to review and merge.
Limits: AI passes run when AI scanning is enabled, and ARGUS analyses code; it does not check the CSP headers your servers send. See ARGUS SAST, or scan a repository free.
Frequently asked questions
How do you prevent XSS?
Encode untrusted data for the context it is written into, rely on your framework's automatic escaping, avoid APIs that bypass it such as innerHTML and dangerouslySetInnerHTML, sanitise any user HTML with a library like DOMPurify, validate URLs, and add a strict Content Security Policy and HttpOnly cookies as a second layer.
How do you prevent XSS in JavaScript?
Use textContent or createElement instead of innerHTML, outerHTML, insertAdjacentHTML or document.write when inserting untrusted data. Treat URL fragments, postMessage data and localStorage as untrusted. If you must insert HTML, sanitise it with DOMPurify first, and only allow http: and https: URLs in links.
Does React prevent XSS?
React escapes values rendered in JSX, which prevents most XSS. It does not protect dangerouslySetInnerHTML, href values containing javascript: URLs, or direct DOM manipulation through refs. Sanitise HTML before using dangerouslySetInnerHTML and validate URLs before rendering them in links.
How do you prevent XSS in Angular?
Use normal interpolation and property binding, which Angular escapes and sanitises automatically. Avoid bypassSecurityTrustHtml and the other bypassSecurityTrust* methods unless the value is fully trusted, avoid direct DOM access through ElementRef, and do not build templates from user input.
What is the difference between stored, reflected and DOM XSS?
Stored XSS saves the payload in your database and serves it to every viewer. Reflected XSS echoes a payload from the current request straight back in the response. DOM-based XSS happens entirely in the browser, when client-side JavaScript writes untrusted data such as the URL fragment into the page.
Is input validation enough to prevent XSS?
No. Input validation helps, but the same data can be safe in one output context and dangerous in another, and validation rules are easy to bypass. The reliable fix is encoding or sanitising at output, for the specific context, with a Content Security Policy as a backstop.
Does a Content Security Policy prevent XSS?
A strict, nonce-based CSP blocks most injected scripts from running, which makes it a strong second layer. It does not fix the underlying bug, can be weakened by unsafe-inline or overly broad allow-lists, and does not stop every attack, so keep output encoding as the primary defence.
Should I sanitise user HTML with regular expressions?
No. HTML parsing has many edge cases, and regex-based filters are routinely bypassed. Use a maintained sanitiser such as DOMPurify in the browser, sanitize-html in Node.js, nh3 or bleach in Python, or the OWASP Java HTML Sanitizer, and keep it updated.
DATA SOURCES
CWE-79: https://cwe.mitre.org/data/definitions/79.html ; OWASP XSS Prevention Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html ; MDN CSP guide