How to Prevent XSS in API: Simple Fixes and Best Practices
To prevent
XSS in your API, always sanitize and validate user inputs and encode outputs before sending them to clients. Use libraries that automatically escape dangerous characters and avoid directly injecting user data into HTML or scripts.Why This Happens
XSS happens when an API accepts user input and sends it back without cleaning it. Attackers can insert harmful scripts that run in users' browsers, stealing data or causing damage.
javascript
const express = require('express'); const app = express(); app.use(express.json()); app.post('/comment', (req, res) => { // Dangerous: directly sending user input back const userComment = req.body.comment; res.send(`<p>User comment: ${userComment}</p>`); }); app.listen(3000);
Output
<p>User comment: <script>alert('XSS')</script></p>
The Fix
Fix this by escaping special characters in user input before sending it back. This stops scripts from running and shows them as plain text instead.
javascript
const express = require('express'); const app = express(); app.use(express.json()); function escapeHtml(text) { return text .replace(/&/g, '&') .replace(/</g, '<') .replace(/>/g, '>') .replace(/"/g, '"') .replace(/'/g, '''); } app.post('/comment', (req, res) => { const userComment = escapeHtml(req.body.comment); res.send(`<p>User comment: ${userComment}</p>`); }); app.listen(3000);
Output
<p>User comment: <script>alert('XSS')</script></p>
Prevention
- Always validate and sanitize all user inputs on the server side.
- Use libraries or frameworks that automatically escape output, like templating engines.
- Never trust user data; treat it as unsafe by default.
- Set proper HTTP headers like
Content-Security-Policyto limit script execution. - Use security linters and automated tests to catch XSS risks early.
Related Errors
Other common security issues include SQL Injection, where attackers insert harmful database commands, and CSRF (Cross-Site Request Forgery), where attackers trick users into unwanted actions. Both require input validation and security headers to fix.
Key Takeaways
Always sanitize and escape user inputs before including them in API responses.
Use safe templating or escaping libraries to prevent script injection.
Never trust user data; validate and clean it on the server side.
Set security headers like Content-Security-Policy to reduce XSS risks.
Test your API for XSS vulnerabilities regularly using automated tools.