JAVASCRIPT
Robust Server-Side Input Validation in Node.js (Express)
Implement robust server-side input validation for API endpoints in Node.js using `express-validator` to protect against malicious data, injection attacks, and ensure data integrity.
const express = require('express');
const { body, validationResult } = require('express-validator');
const app = express();
const PORT = 3000;
// Middleware to parse JSON bodies
app.use(express.json());
// User registration endpoint with validation
app.post('/register',
[
// Validate email format and presence
body('email')
.isEmail().withMessage('Please provide a valid email address')
.normalizeEmail(), // Sanitize email to lowercase and remove dots
// Validate password strength and presence
body('password')
.isLength({ min: 8 }).withMessage('Password must be at least 8 characters long')
.matches(/[A-Z]/).withMessage('Password must contain at least one uppercase letter')
.matches(/[a-z]/).withMessage('Password must contain at least one lowercase letter')
.matches(/[0-9]/).withMessage('Password must contain at least one number')
.matches(/[^A-Za-z0-9]/).withMessage('Password must contain at least one special character'),
// Validate username presence and length
body('username')
.trim() // Trim whitespace from both ends
.notEmpty().withMessage('Username is required')
.isLength({ min: 3, max: 20 }).withMessage('Username must be between 3 and 20 characters'),
// Validate optional age field, ensuring it's an integer if present
body('age').optional().isInt({ min: 18 }).withMessage('Age must be an integer and at least 18.')
],
(req, res) => {
// Check for validation errors
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
// If validation passes, process the registration
const { email, password, username, age } = req.body;
console.log(`User registered: ${username} (${email}), Age: ${age || 'not provided'}`);
// In a real application, you would hash the password and save user to database here
res.status(201).json({ message: 'User registered successfully!' });
}
);
// Start the server
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
How it works: This Node.js snippet demonstrates robust server-side input validation for an Express.js application using the popular `express-validator` library. It defines a set of validation rules for a user registration endpoint, checking for email format, password strength (length, uppercase, lowercase, number, special character), username presence and length, and optional age validation. If validation errors occur, the server responds with a 400 status code and a detailed list of errors, preventing malformed or malicious data from reaching the application's core logic or database.