JAVASCRIPT

Implement Robust Server-Side Input Validation in Node.js

Validate and sanitize incoming request data on the server-side in Node.js to prevent common vulnerabilities like injection attacks and ensure data integrity.

const express = require('express');
const app = express();
app.use(express.json()); // Middleware to parse JSON request bodies

function validateUserData(req, res, next) {
  const { username, email, password, age } = req.body;

  // Validate username: Must be a string, alphanumeric, between 3-20 chars
  if (typeof username !== 'string' || !/^[a-zA-Z0-9]+$/.test(username) || username.length < 3 || username.length > 20) {
    return res.status(400).json({ error: 'Username must be alphanumeric and between 3-20 characters.' });
  }

  // Validate email: Must be a string and follow a basic email regex pattern
  // Note: For production, consider a more robust email validator or library
  if (typeof email !== 'string' || !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) {
    return res.status(400).json({ error: 'Invalid email format.' });
  }

  // Validate password: Must be a string, minimum length (e.g., 8 characters)
  if (typeof password !== 'string' || password.length < 8) {
    return res.status(400).json({ error: 'Password must be at least 8 characters long.' });
  }

  // Validate age: Must be a number, integer, and within a reasonable range
  if (typeof age !== 'number' || !Number.isInteger(age) || age < 0 || age > 120) {
    return res.status(400).json({ error: 'Age must be a valid number between 0 and 120.' });
  }

  // If all validations pass, proceed to the next middleware or route handler
  next();
}

app.post('/register', validateUserData, (req, res) => {
  const { username, email, password, age } = req.body;
  // In a real application, you would hash the password here (see bcrypt snippet)
  // and then save the user data to a database.
  res.status(201).json({ message: 'User registered successfully!', user: { username, email, age } });
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});
How it works: This Node.js snippet demonstrates robust server-side input validation for user registration data within an Express.js application. The `validateUserData` middleware checks the `username`, `email`, `password`, and `age` fields against predefined rules for type, format (using regex), and length/range. By performing these checks early in the request lifecycle, it prevents malformed or malicious data from reaching business logic or databases, significantly reducing the risk of injection vulnerabilities and ensuring data integrity.

Need help integrating this into your project?

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

Hire DigitalCodeLabs