What Is XSS and How Do You Prevent It in Web Applications?

Cross-site scripting (XSS) is a flaw where a web application includes untrusted data in a page without proper encoding, so an attacker's script runs in another user's browser. It can steal sessions, change page content or perform actions as the victim. Developers prevent XSS mainly through context-aware output encoding, which modern frameworks such as React, Angular, Vue and Django apply by default.

Jun 27, 2025 - 15:25
Updated: 
101.7k

Web & API Security in Cybersecurity & Ethical Hacking · Tutorial

What Is XSS and How Do You Prevent It in Web Applications?

Quick answer: Cross-site scripting (XSS) is a flaw where a web application includes untrusted data in a page without proper encoding, so an attacker's script runs in another user's browser. It can steal sessions, change page content or perform actions as the victim. Developers prevent XSS mainly through context-aware output encoding, which modern frameworks such as React, Angular, Vue and Django apply by default. The biggest risks come from escape hatches like dangerouslySetInnerHTML, v-html, bypassSecurityTrust methods and the safe filter. Sanitise any HTML you must render with a library such as DOMPurify, and add a strict Content Security Policy and Trusted Types as extra layers.

Key takeaways

  • XSS is tracked as CWE-79 and sits in the OWASP Top 10 injection category.
  • Encode output for its context: HTML, attribute, JavaScript or URL.
  • Trust your framework's default escaping and audit every bypass.
  • Sanitise rich HTML; never build HTML strings from user input.
  • CSP and Trusted Types limit damage if a bug slips through.

Table of Contents

What Is XSS and Why Should Developers Care?

CWE-79 defines XSS as improper neutralisation of input during web page generation. There are three main types: stored (saved in a database and shown to others), reflected (bounced back from a request) and DOM-based (created by client-side JavaScript). For a fuller conceptual guide, read our sibling article what is cross-site scripting and how can it be prevented. This post focuses on what you change in your code.

How Do Popular Frameworks Protect Against XSS?

FrameworkSafe defaultEscape hatch to audit
ReactJSX escapes values in text and attributesdangerouslySetInnerHTML, javascript: URLs in href
AngularTreats values as untrusted and sanitises themDomSanitizer bypassSecurityTrust methods
VueMustache syntax escapes HTMLv-html, dynamic URL bindings
Django templatesAuto-escaping on by defaultsafe filter, mark_safe, autoescape off
Jinja2 (Flask)Auto-escaping for HTML templates in Flasksafe filter, Markup()

See the official guides from React, Angular, Vue and Django. In plain JavaScript, prefer textContent over innerHTML:

// Safer: the browser treats the value as text, not markup
element.textContent = userComment;

How Do You Render User HTML Safely?

If users must submit formatted content, sanitise it with a maintained allow-list library such as DOMPurify before rendering. A React example:

import DOMPurify from 'dompurify';

function Comment({ html }) {
  const clean = DOMPurify.sanitize(html);
  return <div dangerouslySetInnerHTML={{ __html: clean }} />;
}

Also validate URLs so only http and https schemes are allowed in links, and keep the sanitiser updated. The OWASP XSS Prevention Cheat Sheet lists encoding rules per context, and the DOM-based cheat sheet covers risky browser APIs.

How Do CSP and Trusted Types Add Defence in Depth?

A Content Security Policy tells the browser which scripts may run. A nonce-based policy blocks injected inline scripts:

Content-Security-Policy: script-src 'nonce-RANDOM' 'strict-dynamic'; object-src 'none'; base-uri 'none'

Generate a fresh random nonce per response. Trusted Types go further by making dangerous DOM sinks such as innerHTML reject plain strings in supporting browsers. Also set session cookies as HttpOnly and Secure.

LayerWhat it stops
Output encodingMost XSS at the source
HTML sanitisingMalicious markup in rich content
CSPExecution of injected scripts
Trusted TypesUnsafe writes to DOM sinks
HttpOnly cookiesSession theft through script

What Should a Code Review Check for XSS?

  • Search the codebase for innerHTML, dangerouslySetInnerHTML, v-html, bypassSecurityTrust, mark_safe and the safe filter.
  • Confirm every match uses sanitised or trusted data.
  • Check that user-controlled URLs are validated.
  • Run SAST in CI and a DAST tool such as OWASP ZAP on staging.
  • Test only applications you own or are authorised to test, as required by India's IT Act 2000.

XSS is one of several common risks covered in our guide to OWASP Top 10 vulnerabilities. Learn secure coding hands-on in our web application security training.

References

Frequently Asked Questions

Cross-site scripting is a vulnerability where untrusted data is placed in a web page without proper encoding, letting an attacker’s script run in other users’ browsers.

React escapes values rendered through JSX by default, but dangerouslySetInnerHTML and unvalidated javascript: URLs can still introduce XSS if used carelessly.

No. Validation helps, but the main defence is context-aware output encoding, supported by sanitising rich HTML and a strict Content Security Policy.

Encoding turns special characters into safe text so markup is not interpreted, while sanitising removes dangerous parts from HTML you intend to render.

DOM-based XSS happens entirely in client-side JavaScript, when code writes untrusted data such as URL fragments into risky DOM sinks like innerHTML.

CSP tells the browser which scripts are allowed, so injected scripts without a valid nonce or approved source are blocked from running.

Trusted Types is a browser feature that makes dangerous DOM sinks accept only approved typed values instead of plain strings, reducing DOM-based XSS.

They do not stop XSS itself, but they prevent scripts from reading session cookies, which limits one of the most serious consequences.

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Wow Wow 0
Sad Sad 0
Angry Angry 0
Vaishnavi

Vaishnavi is a skilled tech professional at the Ethical Hacking Training Institute in Pune, responsible for managing and optimizing the technical infrastructure that supports advanced cybersecurity education. With deep expertise in network security, backend operations, and system performance, she ensures that practical labs, online modules, and assessments run smoothly and securely. Her behind-the-scenes contributions play a vital role in delivering a seamless and secure learning experience for aspiring ethical hackers.