Express XSS Prevention - HTML Escaping Codemod
This codemod automatically fixes Cross-Site Scripting (XSS) vulnerabilities in Express.js applications by transforming res.send() calls that concatenate user input directly into HTML strings. It adds proper HTML escaping using the escape-html library to prevent XSS attacks.
What it fixes
Direct concatenation of user input in res.send() calls creates XSS vulnerabilities. This codemod identifies these patterns and automatically adds HTML escaping:
String Concatenation
Before:
javascript
After:
javascript
Template Literals
Before:
javascript
After:
javascript
Complex Patterns
Before:
javascript
After:
javascript
Installation & Usage
bash
What gets transformed
✅ Transformed:
res.send()calls with HTML content and user variables- String concatenation patterns with HTML tags
- Template literals with HTML and variables
- Member expressions like
req.query.name,req.body.data - Multiple variables in the same HTML string
❌ Not transformed:
- Static HTML strings without variables
- Already escaped content using
escape-htmlor similar - JSON responses (
res.json()) - Plain text without HTML tags
- Status code responses
- Test files (
.test.js,.spec.js)
Security Impact
This codemod helps prevent CWE-79: Cross-site Scripting (XSS) vulnerabilities by:
- Input Sanitization: Wraps user input in
escapeHtml()calls - Automatic Import: Adds
require('escape-html')when needed - Safe Defaults: Only transforms risky patterns, preserves safe code
- No Double-Escaping: Detects already escaped content
Requirements
- Node.js application using Express.js
- JavaScript or TypeScript files
- Will automatically install
escape-htmldependency
Edge Cases Handled
- ✅ Already escaped content (prevents double-escaping)
- ✅ Multiple variables in single expression
- ✅ Nested member expressions (
req.body.user.name) - ✅ Mixed string concatenation and template literals
- ✅ Existing import statements (preserves order)
Development
bash
Security References
- CWE-79: Cross-site Scripting (XSS)
- OWASP XSS Prevention Cheat Sheet
- Express.js Security Best Practices
- escape-html npm package
License
MIT