JAVASCRIPT
Server-Side Input Sanitization for XSS Prevention
Sanitize user-provided input on the server-side to prevent Cross-Site Scripting (XSS) attacks, ensuring only safe content is processed and displayed.
const express = require('express');
const bodyParser = require('body-parser');
const { body, validationResult } = require('express-validator'); // npm install express-validator
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Simple sanitization utility (for demonstration - a more robust library like 'sanitize-html' is recommended if allowing some HTML).
// For pure text input, simply encoding HTML entities is often sufficient.
function sanitizeTextForXSS(input) {
// Basic escaping of HTML entities for pure text output
if (typeof input !== 'string') return input;
return input
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
app.post('/submit-comment',
// Validate and sanitize the comment field
body('comment')
.trim() // Remove leading/trailing whitespace
.notEmpty().withMessage('Comment cannot be empty')
.isLength({ min: 5, max: 500 }).withMessage('Comment must be between 5 and 500 characters')
.customSanitizer(value => sanitizeTextForXSS(value)), // Apply custom XSS sanitization
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const sanitizedComment = req.body.comment;
// In a real application, save sanitizedComment to database or use it safely
console.log('Received sanitized comment:', sanitizedComment);
res.status(200).send(`Comment received and sanitized: ${sanitizedComment}`);
}
);
app.get('/', (req, res) => {
res.send(`
<html>
<body>
<h1>Submit a Comment</h1>
<form action="/submit-comment" method="POST">
<textarea name="comment" rows="5" cols="40"></textarea><br>
<button type="submit">Submit</button>
</form>
<p>Try entering: <script>alert('XSS');</script> or <img src=x onerror=alert('XSS')></p>
</body>
</html>
`);
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
How it works: This snippet illustrates server-side input sanitization in an Express.js application using `express-validator`. It demonstrates how to trim whitespace, validate length, and apply a custom sanitizer (`sanitizeTextForXSS`) to convert potentially malicious HTML characters (like `<` and `>`) into their HTML entities. This crucial step prevents Cross-Site Scripting (XSS) attacks by ensuring that user-provided input is safe before it's stored or displayed.