JAVASCRIPT

Robust Server-Side Input Schema Validation

Implement robust server-side input validation using a schema definition library like Joi to protect against malformed data and ensure data integrity in your API endpoints.

const Joi = require('joi');
const express = require('express');
const app = express();
app.use(express.json());

const userSchema = Joi.object({
    username: Joi.string().alphanum().min(3).max(30).required(),
    email: Joi.string().email({ minDomainSegments: 2, tlds: { allow: ['com', 'net', 'org'] } }).required(),
    password: Joi.string().pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')).required(), // Example: basic pattern, not strong
    isAdmin: Joi.boolean().default(false)
});

app.post('/api/users', (req, res) => {
    const { error, value } = userSchema.validate(req.body, { abortEarly: false }); // abortEarly: false collects all errors

    if (error) {
        return res.status(400).json({
            message: 'Validation failed',
            details: error.details.map(d => d.message)
        });
    }

    // If validation passes, 'value' contains the validated and potentially coerced data
    // For example, if 'isAdmin' was missing, it would be 'false' due to .default(false)
    console.log('Validated data:', value);
    res.status(201).json({ message: 'User created successfully', user: value });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

// To run this:
// 1. npm init -y
// 2. npm install express joi
// 3. Save as app.js and run node app.js
// Test with:
// curl -X POST -H "Content-Type: application/json" -d '{"username": "john_doe", "email": "[email protected]", "password": "securepassword123"}' http://localhost:3000/api/users
// curl -X POST -H "Content-Type: application/json" -d '{"username": "jo", "email": "invalid-email", "password": "abc"}' http://localhost:3000/api/users
How it works: This snippet demonstrates robust server-side input validation using the Joi library in a Node.js Express application. It defines a schema (`userSchema`) that specifies the expected structure, data types, and constraints for incoming user data (e.g., `username` must be alphanumeric, `email` must be a valid email format, `password` must match a pattern). When a request comes to `/api/users`, `userSchema.validate()` checks the request body against this schema. If validation fails, a `400 Bad Request` response is sent with detailed error messages, preventing malformed or malicious data from reaching your application logic or database. This is critical for data integrity and security, guarding against a wide range of vulnerabilities beyond simple XSS or SQL injection.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs