JAVASCRIPT

Robust Server-Side Input Validation for API Endpoints

Implement comprehensive server-side input validation for Node.js Express APIs using `express-validator` to ensure data integrity and prevent various attacks.

const express = require('express');
const { body, validationResult } = require('express-validator');

const app = express();
app.use(express.json()); // For parsing application/json

const registerValidationRules = () => {
  return [
    body('username')
      .trim()
      .notEmpty().withMessage('Username is required.')
      .isLength({ min: 3 }).withMessage('Username must be at least 3 characters long.')
      .matches(/^[a-zA-Z0-9_]+$/).withMessage('Username can only contain letters, numbers, and underscores.'),
    body('email')
      .trim()
      .isEmail().withMessage('Please enter a valid email address.')
      .normalizeEmail(), // Sanitizes email to canonical form
    body('password')
      .isLength({ min: 8 }).withMessage('Password must be at least 8 characters long.')
      .matches(/\d/).withMessage('Password must contain a number.')
      .matches(/[a-z]/).withMessage('Password must contain a lowercase letter.')
      .matches(/[A-Z]/).withMessage('Password must contain an uppercase letter.')
      .matches(/[^a-zA-Z0-9]/).withMessage('Password must contain a special character.'),
    body('confirmPassword').custom((value, { req }) => {
      if (value !== req.body.password) {
        throw new Error('Password confirmation does not match password.');
      }
      return true;
    }),
  ];
};

const validate = (req, res, next) => {
  const errors = validationResult(req);
  if (errors.isEmpty()) {
    return next();
  }
  const extractedErrors = [];
  errors.array().map(err => extractedErrors.push({ [err.param]: err.msg }));

  return res.status(422).json({
    errors: extractedErrors,
  });
};

app.post('/api/register', registerValidationRules(), validate, (req, res) => {
  // If validation passes, process the registration
  // For security, remember to hash the password before saving!
  res.status(200).json({ message: 'Registration successful!', user: { username: req.body.username, email: req.body.email } });
});

const PORT = process.env.PORT || 3004;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
How it works: This snippet provides a robust approach to server-side input validation using `express-validator` in a Node.js Express application. Beyond basic sanitization, it enforces strict rules for data types, lengths, formats (e.g., email regex, password complexity), and relationships between fields (e.g., confirm password). Comprehensive validation is a critical security layer that prevents a wide range of attacks, including buffer overflows, logic bombs, and data integrity violations, by ensuring that only well-formed and expected data is processed by the application.

Need help integrating this into your project?

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

Hire DigitalCodeLabs