0
0
ExpressHow-ToBeginner · 4 min read

How to Sanitize Input in Express for Secure Web Apps

To sanitize input in Express, use middleware like express-validator which provides sanitization methods to clean user data before processing. You add sanitization chains in your route handlers to trim, escape, or normalize inputs safely.
📐

Syntax

Use express-validator middleware functions in your route to sanitize inputs. Common sanitizers include trim() to remove spaces, escape() to convert HTML characters, and normalizeEmail() for emails.

Example usage in a route:

  • body('fieldName').trim().escape() - sanitizes the field named 'fieldName'
  • check('fieldName').normalizeEmail() - sanitizes email input
javascript
import express from 'express';
import { body } from 'express-validator';

const app = express();
app.use(express.json());

app.post('/submit', [
  body('username').trim().escape(),
  body('email').normalizeEmail()
], (req, res) => {
  res.send(req.body);
});
💻

Example

This example shows how to sanitize user input for username and email fields using express-validator. It trims spaces, escapes HTML in username, and normalizes the email format.

javascript
import express from 'express';
import { body, validationResult } from 'express-validator';

const app = express();
app.use(express.json());

app.post('/register', [
  body('username').trim().escape(),
  body('email').normalizeEmail()
], (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  res.json({ sanitizedData: req.body });
});

app.listen(3000, () => console.log('Server running on port 3000'));
Output
Server running on port 3000 POST /register with body {"username": " <b>John</b> ", "email": "JOHN@Example.COM "} Response: {"sanitizedData":{"username":"&lt;b&gt;John&lt;/b&gt;","email":"john@example.com"}}
⚠️

Common Pitfalls

Common mistakes when sanitizing input in Express include:

  • Not using sanitization middleware, which leaves inputs vulnerable to injection attacks.
  • Confusing validation with sanitization; validation checks correctness, sanitization cleans data.
  • Sanitizing only some fields and missing others.
  • Not handling validation errors properly after sanitization.

Always combine validation and sanitization and handle errors to ensure safe and clean input.

javascript
import express from 'express';
import { body, validationResult } from 'express-validator';

const app = express();
app.use(express.json());

// Wrong: No sanitization
app.post('/wrong', [
  body('username').isLength({ min: 3 })
], (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  res.send(req.body);
});

// Right: Validation + sanitization
app.post('/right', [
  body('username').trim().escape().isLength({ min: 3 })
], (req, res) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  res.send(req.body);
});
📊

Quick Reference

Here are common sanitization methods from express-validator:

SanitizerDescription
trim()Removes whitespace from both ends of a string
escape()Converts HTML characters to safe entities
normalizeEmail()Normalizes email addresses to lowercase and standard format
toInt()Converts input to an integer
toFloat()Converts input to a floating-point number
blacklist(chars)Removes specified characters from input
whitelist(chars)Allows only specified characters in input

Key Takeaways

Use express-validator middleware to sanitize inputs in Express routes.
Sanitization cleans data by trimming, escaping, or normalizing inputs to prevent security risks.
Always combine input validation and sanitization for safe and reliable data handling.
Handle validation errors properly to avoid processing bad input.
Sanitize all user inputs consistently to avoid vulnerabilities.