JAVASCRIPT
Server-Side Input Validation and Sanitization with Express.js
Implement robust server-side input validation and sanitization using `express-validator` to prevent common web vulnerabilities like XSS, SQL injection, and malformed data.
const express = require('express');
const { body, validationResult } = require('express-validator');
const app = express();
app.use(express.json()); // For parsing application/json
app.post(
'/register',
[
// Validate and sanitize username
body('username')
.trim() // Remove whitespace from both ends
.notEmpty() // Ensure it's not empty
.isLength({ min: 3, max: 20 }).withMessage('Username must be 3-20 characters long')
.escape(), // Escape HTML characters to prevent XSS
// Validate and sanitize email
body('email')
.trim()
.notEmpty().withMessage('Email is required')
.isEmail().withMessage('Invalid email format')
.normalizeEmail(), // Standardize email format
// Validate password
body('password')
.notEmpty().withMessage('Password is required')
.isLength({ min: 8 }).withMessage('Password must be at least 8 characters long')
.matches(/[a-z]/).withMessage('Password must contain a lowercase letter')
.matches(/[A-Z]/).withMessage('Password must contain an uppercase letter')
.matches(/[0-9]/).withMessage('Password must contain a number')
.matches(/[^A-Za-z0-9]/).withMessage('Password must contain a special character'),
],
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
// If validation passes, the sanitized data is available in req.body
const { username, email, password } = req.body;
// In a real application, hash the password before saving
// and save the user to the database.
console.log('User Registered:', { username, email });
res.status(201).send('User registered successfully!');
}
);
app.get('/', (req, res) => {
res.send('Welcome to the registration page example.');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
How it works: This snippet demonstrates server-side input validation and sanitization using `express-validator` for an Express.js application. It defines rules to trim whitespace, ensure fields are not empty, check data formats (e.g., email), enforce password policies, and escape HTML characters (`.escape()`) to prevent Cross-Site Scripting (XSS). If validation fails, appropriate error messages are returned. This process is crucial for preventing various injection attacks and maintaining data integrity.