100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace

Cross-Site Scripting (XSS) Prevention Cheat Sheet

Cross-Site Scripting (XSS) Prevention Cheat Sheet

Covers the three main XSS variants and concrete output-encoding, sanitization, and CSP techniques to prevent script injection in web apps.

2 PagesIntermediateFeb 5, 2026

Types of XSS

The three primary categories of cross-site scripting.

  • Stored (persistent)- Malicious script saved on the server (e.g. in a comment) and served to other users
  • Reflected- Script included in a request (e.g. URL param) and immediately reflected back in the response
  • DOM-based- Vulnerability exists entirely in client-side JS that writes untrusted data into the DOM

Safe Output Rendering (JavaScript)

Avoiding unsafe DOM sinks and encoding output correctly.

javascript
// UNSAFE: innerHTML executes any injected <script>/event handlerselement.innerHTML = userInput;// SAFE: textContent treats input as plain text, no HTML parsingelement.textContent = userInput;// If HTML must be rendered, sanitize firstimport DOMPurify from 'dompurify';element.innerHTML = DOMPurify.sanitize(userInput);

Content Security Policy Header

Restricts which sources scripts can be loaded from as a defense-in-depth layer.

http
Content-Security-Policy: default-src 'self'; \  script-src 'self' https://trusted-cdn.com; \  object-src 'none'; \  base-uri 'self'

Prevention Checklist

Core practices to reduce XSS risk across an application.

  • Context-aware output encoding- Encode differently for HTML body, attribute, JS, URL, and CSS contexts
  • Use safe DOM APIs- Prefer textContent/setAttribute over innerHTML/document.write
  • Sanitize rich HTML- Use a vetted library like DOMPurify when HTML input must be allowed
  • HttpOnly cookies- Prevent JavaScript from reading session cookies via document.cookie
  • Content-Security-Policy- Blocks inline scripts and untrusted origins even if injection occurs
  • Framework auto-escaping- React/Vue/Angular escape output by default — avoid dangerouslySetInnerHTML/v-html unless sanitized
Pro Tip

Auto-escaping in frameworks like React only protects the rendered DOM text — it won't stop XSS from unsafe href/src attribute values like javascript: URIs, so validate and allow-list URL schemes separately.

Was this cheat sheet helpful?

Explore Topics

#CrossSiteScriptingXSSPrevention#CrossSiteScriptingXSSPreventionCheatSheet#Cybersecurity#Intermediate#TypesOfXSS#Safe#Output#Rendering#Security#WebDevelopment#CommandLine#CheatSheet#SkillVeris