Skip to main content
skill CX Codex

xss-prevention — Claude Code skill: install guide

The xss-prevention skill helps prevent XSS with input sanitization, output encoding, and CSP. Use it for user HTML, comments, rich text, and script injection issues.

MIT 320 installs ★ 250 updated 2026-10-20

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add secondsky/claude-skills --skill xss-prevention -a claude-code
Open on GitHub

What xss-prevention does

The skill covers stored, reflected, DOM-based, and mutation XSS. It explains how to encode values for HTML, attributes, JavaScript, URLs, and CSS, and how to sanitize rich content with an allowlist through DOMPurify. URL checks accept http: and https: protocols.

Examples target Node.js, Express, and React. They show textContent, setAttribute, and document.createTextNode, plus CSP headers with a nonce. The guidance also flags eval(), document.write(), string-based timers, inline handlers, and user-controlled innerHTML. Reference material includes Python, Flask, and Django patterns. Passing unsanitized rich text to dangerouslySetInnerHTML leaves an XSS exposure.

The skill can be installed for Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, and OpenCode. The HTML examples use DOMPurify, while the server examples use Node.js and Express.

What it helps with

  • sanitize HTML from user-generated content
  • encode output for its rendering context
  • configure CSP headers in Express
  • validate a URL before creating a link
  • replace unsafe DOM calls with safer APIs

Example prompts for the agent

  • Review the comment form for stored and reflected XSS, then suggest fixes.
  • Sanitize the HTML passed to RichContent with DOMPurify and an allowlist.
  • Set up nonce-based CSP middleware for Express and remove unsafe innerHTML and eval() usage.

How to install xss-prevention

1Skills CLI (Vercel)

npx skills add secondsky/claude-skills --skill xss-prevention -a claude-code

2Manually: put the files in place

~/.claude/skills/xss-prevention/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/xss-prevention/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about xss-prevention

How do I install xss-prevention in Claude Code?

Run npx skills add secondsky/claude-skills --skill xss-prevention -a claude-code, then check ~/.claude/skills/xss-prevention/SKILL.md.

What does xss-prevention do?

It guides XSS prevention with input sanitization, context-aware output encoding, safer DOM APIs, and Content Security Policy. The material covers stored, reflected, DOM-based, and mutation XSS.

Is DOMPurify needed for rich text?

For HTML from a rich text editor, the skill uses DOMPurify with an allowlist of tags and attributes. In React, the sanitized result can be passed to dangerouslySetInnerHTML.

Source text

SKILL.md · MIT
---
name: xss-prevention
description: "XSS attack prevention with input sanitization, output encoding, Content Security Policy. Use for user-generated content, rich text editors, web application security, or encountering stored XSS, reflected XSS, DOM manipulation, script injection errors."

metadata:
  keywords:
    - sanitization
    - HTML-encoding
    - DOMPurify
    - CSP
    - Content-Security-Policy
    - rich-text-editor
    - user-input
    - escaping
    - innerHTML
    - DOM-manipulation
    - stored-XSS
    - reflected-XSS
    - input-validation
    - output-encoding
    - trusted-types
    - XSS-attacks
    - web-security
    - user-generated-content
    - secure-coding
    - script-injection
    - DOM-based-XSS

license: MIT
---
# XSS Prevention

## Overview

Implement comprehensive Cross-Site Scripting attack prevention through input sanitization, output encoding, Content Security Policy headers, and secure coding practices.

## When to Use

- User-generated content display
- Rich text editors
- Comment systems
- Search functionality
- Dynamic HTML generation
- Template rendering scenarios

## XSS Attack Types

| Type | Vector | Defense |
|------|--------|---------|
| Reflected | URL parameters | Output encoding |
| Stored | Database content | Input sanitization |
| DOM-based | Client-side JS | Safe DOM APIs |
| Mutation | HTML parser quirks | Strict sanitization |

## Output Encoding (Node.js)

```javascript
function encodeHTML(str) {
  return str
    .replace(/&/g, '&')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#x27;');
}

function encodeForAttribute(str) {
  return str.replace(/[^\w.-]/g, char =>
    `&#x${char.charCodeAt(0).toString(16)};`
  );
}

// Usage in templates
app.get('/profile', (req, res) => {
  const username = encodeHTML(req.query.name);
  res.send(`<h1>Welcome, ${username}</h1>`);
});
```

## DOMPurify Sanitization

```javascript
import DOMPurify from 'dompurify';

const config = {
  ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a', 'p', 'br'],
  ALLOWED_ATTR: ['href', 'title'],
  ALLOW_DATA_ATTR: false
};

function sanitizeHTML(dirty) {
  return DOMPurify.sanitize(dirty, config);
}

// React component
function RichContent({ html }) {
  return (
    <div dangerouslySetInnerHTML={{ __html: sanitizeHTML(html) }} />
  );
}
```

## Content Security Policy

```javascript
// Express middleware
app.use((req, res, next) => {
  const nonce = crypto.randomBytes(16).toString('base64');
  res.locals.nonce = nonce;

  res.setHeader('Content-Security-Policy', [
    "default-src 'self'",
    `script-src 'self' 'nonce-${nonce}'`,
    "style-src 'self' 'unsafe-inline'",
    "img-src 'self' data: https:",
    "connect-src 'self' https://api.example.com",
    "frame-ancestors 'none'",
    "base-uri 'self'",
    "form-action 'self'"
  ].join('; '));

  next();
});
```

## Safe DOM APIs

❌ NEVER do any of the following with user-controlled input — these are XSS
sinks and there is no safe way to call them with untrusted data:

- Assign it to `element.innerHTML` / `element.outerHTML`
- Pass it to `eval()`
- Pass it to `document.write()`
- Pass it to `setTimeout` / `setInterval` as a string
- Insert it into an inline event handler (e.g. `onclick="..."`)

```javascript
// SAFE — use these instead
element.textContent = userInput;      // Escaped automatically
element.setAttribute('data-id', id);  // Safe for attributes
document.createTextNode(userInput);   // Creates safe text node
```

The safe patterns above (`textContent`, attribute escaping via `setAttribute`,
`DOMPurify.sanitize`) are the only correct ways to handle user input in the DOM.

## URL Validation

```javascript
function isSafeURL(url) {
  try {
    const parsed = new URL(url);
    return ['http:', 'https:'].includes(parsed.protocol);
  } catch {
    return false;
  }
}

// Usage
const href = isSafeURL(userURL) ? userURL : '#';
```

## Context-Specific Encoding

Different contexts require different encoding approaches:

- **HTML Entity Encoding**: Safest option for text content
- **Attribute Encoding**: For HTML attributes
- **JavaScript Escaping**: For script contexts
- **URL Encoding**: For URL parameters
- **CSS Escaping**: For stylesheet contexts

Always encode output by the specific context where data will be rendered.

## Additional Implementations

See [references/python-sanitization.md](references/python-sanitization.md) for:
- Python bleach library usage
- Flask/Django template escaping
- Server-side validation patterns

See [references/nodejs-advanced.md](references/nodejs-advanced.md) for:
- Complete XSSPrevention class with all methods
- Express middleware (xssProtection)
- React components (SafeText, SafeHTML, SafeLink, useSanitizedInput)
- Helmet CSP configuration

## Best Practices

**✅ DO:**
- Encode output by default
- Use templating engines with auto-escaping
- Implement CSP headers
- Sanitize rich content with allowlists
- Validate URLs with protocol whitelisting
- Use HTTPOnly cookies
- Conduct regular security testing
- Leverage secure frameworks

**❌ DON'T:**
- Trust user input
- Use unsafe functions (eval, innerHTML)
- Disable security features for convenience
- Rely solely on client-side validation
- Use blocklists instead of allowlists
- Skip context-specific encoding
- Allow arbitrary script execution

## Security Checklist

- [ ] Encode all output by context (HTML, attribute, JS)
- [ ] Sanitize HTML with allowlist (not blocklist)
- [ ] Implement strict CSP headers
- [ ] Use HTTPOnly cookies for sessions
- [ ] Validate and sanitize URLs
- [ ] Avoid innerHTML with user content
- [ ] Regular security testing

## Resources

- [OWASP XSS Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html)
- [DOMPurify Documentation](https://github.com/cure53/DOMPurify)
- [Content Security Policy Reference](https://content-security-policy.com/)
- [Web Security by Mozilla](https://developer.mozilla.org/en-US/docs/Web/Security)

© secondsky · MIT · secondsky/claude-skills

Similar skills

All skills for Security →

From the same set138

The whole set →
design-review design-review is a Claude Code skill for seven-phase frontend audits covering interactive states, responsive testing, visual polish, and WCAG 2.1 AA compliance. CX Codex +1 327installs cloudflare-workers-ci-cd cloudflare-workers-ci-cd — a skill that walks your agent through CI/CD for Cloudflare Workers on GitHub Actions or GitLab CI. Useful when a pipeline breaks or every pull request needs its own preview. CX Codex +1 326installs cloudflare-workers-dev-experience cloudflare-workers-dev-experience guides local Cloudflare Workers development using Wrangler and Miniflare. Helps fix broken bindings for KV, D1, or R2, configure HMR, and set up tsconfig. CX Codex +1 324installs cloudflare-workers-observability A skill for Cloudflare Workers observability: structured logging, Analytics Engine, Tail Workers, metrics and alerting. Useful when a worker fails in production and you can't see why. CX Codex +1 322installs cloudflare-workers-multi-lang cloudflare-workers-multi-lang guides Cloudflare Workers development in Rust, Python, and WebAssembly. Useful when offloading heavy computation to WASM modules. CX Codex +1 317installs cloudflare-r2 Skill for working with Cloudflare R2, an S3-compatible object storage. Manages buckets, uploads, CORS and presigned URLs — everything needed to handle files in the cloud. CX Codex +1 316installs cloudflare-workers-migration cloudflare-workers-migration — a skill for porting applications to Cloudflare Workers from AWS Lambda, Vercel, Express and Node.js. Adapts handlers, middleware and environment variables to Web APIs. CX Codex +1 316installs tanstack-query This skill guides Claude Code through TanStack Query v5 for fetching, caching, mutations, and v4 migration issues in React projects. CX Codex +1 314installs

Project sponsors

Companies that keep this analytics open