What is XSS?
Imagine your website is like a house. XSS (Cross-Site Scripting) is when someone sneaks bad code into your house through a window or door. This bad code can steal information from your visitors or make your website do things it shouldn’t.
⚠️ Real Example
If someone types this into a comment box on your website:
<script>alert('Hacked!')</script>
And your website shows this comment without checking it first, it could show a popup to everyone who visits!
How to Stop XSS Attacks
Here are simple ways to protect your website from XSS attacks:
1. Clean User Input
Always clean any text that comes from users before showing it on your website. Here’s how:
// Simple way to clean text
function cleanText(text) {
return text
.replace(/&/g, '&')
.replace(//g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
// Example: Cleaning a comment
const userComment = "<script>alert('Hacked!')</script>";
const safeComment = cleanText(userComment);
console.log(safeComment); // Shows: <script>alert('Hacked!')</script>
2. Use Content Security Policy (CSP)
CSP is like a security guard for your website. It tells the browser what’s allowed and what’s not.
// Add this to your website's <head> section
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval';">
This tells the browser to only run scripts that come from your own website.
3. Use Safe HTML Libraries
Instead of writing your own code to clean HTML, use a library that’s already tested and safe:
// Using DOMPurify library
import DOMPurify from 'dompurify';
const dirtyHTML = "<script>alert('Hacked!')</script><p>Hello</p>";
const cleanHTML = DOMPurify.sanitize(dirtyHTML);
console.log(cleanHTML); // Shows: <p>Hello</p>
Real-World Examples
Safe Comment System
Here’s how to make a safe comment system:
// HTML
<form id="commentForm">
<textarea id="comment" placeholder="Write your comment..."></textarea>
<button type="submit">Post Comment</button>
</form>
<div id="comments"></div>
// JavaScript
document.getElementById('commentForm').addEventListener('submit', function(e) {
e.preventDefault();
const commentText = document.getElementById('comment').value;
const safeComment = DOMPurify.sanitize(commentText);
const commentDiv = document.createElement('div');
commentDiv.textContent = safeComment; // Using textContent instead of innerHTML
document.getElementById('comments').appendChild(commentDiv);
});
Safe URL Handling
How to safely handle URLs from users:
function isSafeUrl(url) {
// Only allow http and https URLs
return url.startsWith('http://') || url.startsWith('https://');
}
function createSafeLink(url, text) {
if (!isSafeUrl(url)) {
return 'Invalid URL';
}
const safeUrl = encodeURI(url);
const safeText = cleanText(text);
return `<a href="${safeUrl}">${safeText}</a>`;
}
Common Mistakes to Avoid
❌ Don’t Use innerHTML
Using innerHTML is like opening all your windows and doors. Instead, use textContent or createElement.
// ❌ Bad
element.innerHTML = userInput;
// ✅ Good
element.textContent = userInput;
❌ Don’t Trust User Input
Always check and clean any data that comes from users, even if it seems safe.
// ❌ Bad
const userData = req.body;
saveToDatabase(userData);
// ✅ Good
const userData = cleanUserInput(req.body);
saveToDatabase(userData);
Testing Your Website
Here’s a simple way to test if your website is safe from XSS:
// Try these in your forms and see what happens
const testInputs = [
"<script>alert('XSS')</script>",
"<img src='x' onerror='alert(1)'>",
"javascript:alert('XSS')",
"<svg onload='alert(1)'></svg>"
];
If you see any alerts or strange behavior, your website needs more protection!