How to protect against XSS attacks in modern web applications

· Category: Cybersecurity

Short answer

XSS attacks inject malicious scripts into web pages viewed by other users. Prevent XSS by: (1) encoding output before rendering, (2) validating and sanitizing input, (3) implementing Content Security Policy headers, and (4) using framework protections that auto-escape by default. For related security headers, see how to implement Content Security Policy headers.

Three types of XSS

  1. Reflected XSS: Malicious script is in the request (URL parameter) and reflected back in the response. Requires tricking a user into clicking a crafted link.
  2. Stored XSS: Script is stored on the server (in a database) and served to all users who view the page. More dangerous — affects every visitor.
  3. DOM-based XSS: Script manipulates the page's DOM directly in the browser without server involvement.

Prevention strategies

Output encoding

Never insert untrusted data into HTML without encoding:

// Bad - vulnerable to XSS
element.innerHTML = userInput;

// Good - textContent is safe
element.textContent = userInput;

Content Security Policy

Add a CSP header to restrict which scripts can execute:

Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self'

This blocks inline scripts and scripts from external domains.

Framework protections

  • React auto-escapes content in JSX by default
  • Vue auto-escapes {{ }} templates
  • Angular sanitizes values bound to the DOM

Tips

  • Never use innerHTML, document.write(), or eval() with user input
  • Use HTTP-only cookies for session tokens so JavaScript can't read them
  • For broader web security, see what are the OWASP Top 10 security risks