JAVASCRIPT

Validate and Sanitize User Input on Server

Secure your Node.js Express API by validating and sanitizing user input to prevent common vulnerabilities like XSS and SQL injection. Uses express-validator.

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

app.use(express.json());

app.post('/register', [
  body('username').trim().isLength({ min: 3 }).escape(),
  body('email').isEmail().normalizeEmail(),
  body('password').isLength({ min: 6 }).withMessage('Password must be at least 6 characters long'),
], (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }

  // Input is valid and sanitized, process further
  const { username, email, password } = req.body;
  console.log('Valid and sanitized data:', { username, email, password });
  res.status(200).send('User registered successfully');
});

app.listen(3000, () => console.log('Server running on port 3000'));
How it works: This snippet demonstrates robust server-side input validation and sanitization using `express-validator` in a Node.js Express application. It defines validation rules for username, email, and password fields, ensuring data meets specific criteria (e.g., minimum length, email format). Crucially, `.escape()` is used to convert HTML entities in the username, preventing Cross-Site Scripting (XSS) attacks, and `.normalizeEmail()` cleans up email formats. If validation fails, appropriate error messages are returned, safeguarding the application from malformed or malicious input before it reaches the backend logic or database.

Need help integrating this into your project?

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

Hire DigitalCodeLabs