JAVASCRIPT
Server-Side Input Validation for JSON Payloads (Express.js/Joi)
Implement robust server-side input validation for JSON request bodies in Express.js using Joi, ensuring data integrity and preventing malformed input.
const express = require('express');
const Joi = require('joi'); // Joi is a powerful schema description language and validator for JavaScript.
const app = express();
app.use(express.json()); // Middleware to parse JSON request bodies
// Define a Joi schema for user creation
const userSchema = Joi.object({
username: Joi.string().alphanum().min(3).max(30).required(),
email: Joi.string().email().required(),
password: Joi.string().pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')).required(), // Example: alphanumeric, 3-30 chars
age: Joi.number().integer().min(18).max(120)
});
// Middleware for validating request body against a schema
function validateBody(schema) {
return (req, res, next) => {
const { error } = schema.validate(req.body);
if (error) {
return res.status(400).json({ message: error.details[0].message });
}
next(); // If validation passes, proceed to the next middleware/route handler
};
}
// Route to create a new user with validation
app.post('/users', validateBody(userSchema), (req, res) => {
const newUser = req.body;
// In a real application, save newUser to database
console.log('User created:', newUser);
res.status(201).json({ message: 'User created successfully', user: newUser });
});
// Example of invalid request body (try sending this):
/*
{
"username": "ab",
"email": "invalid-email",
"password": "short"
}
*/
// Example of valid request body:
/*
{
"username": "johnDoe",
"email": "[email protected]",
"password": "MySecurePass123",
"age": 30
}
*/
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
How it works: Server-side input validation is crucial for maintaining data integrity and preventing various vulnerabilities. This snippet demonstrates robust validation for JSON request payloads in an Express.js application using the 'Joi' library. It defines a schema (`userSchema`) outlining the expected structure and constraints for incoming user data. A custom `validateBody` middleware then applies this schema to `req.body`. If the input fails validation, a 400 Bad Request error is returned; otherwise, the request proceeds, ensuring that only valid data reaches your application's logic.