Sanitizing Data

Clean and escape input to prevent injection and stored XSS attacks.

Sanitization removes or neutralizes dangerous content in user input, such as HTML that could run scripts (XSS) or characters used in injection attacks.

  • Trim and normalize strings.
  • Escape or strip HTML before storing or displaying it.
  • Use parameterized queries or an ORM so user input can never alter your SQL.

Validation checks the shape; sanitization makes the content safe. Do both.

Example

Example · javascript
const validator = require('validator');

app.post('/comments', (req, res) => {
  const raw = req.body.text || '';
  const clean = validator.escape(raw.trim());
  // 'clean' is now safe to store and display
  res.status(201).json({ text: clean });
});

When to use it

  • A comment submission endpoint sanitises the body text with DOMPurify to strip any injected script tags before storing in the database.
  • A developer trims and lowercases email inputs in a registration middleware to prevent duplicate accounts caused by whitespace or case differences.
  • A search API sanitises the query parameter by removing SQL meta-characters to prevent injection attacks when building dynamic queries.

More examples

Trim and normalise with express-validator

Chains .trim() and .toLowerCase() sanitisers on the email field so whitespace and case differences don't cause duplicate accounts.

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

app.post('/login', [
  body('email').trim().toLowerCase().isEmail(),
  body('password').trim(),
], (req, res) => {
  const errs = validationResult(req);
  if (!errs.isEmpty()) return res.status(400).json({ errors: errs.array() });
  // req.body.email is now trimmed and lowercased
  res.json({ email: req.body.email });
});

Escape HTML to prevent XSS

Uses express-validator's .escape() sanitiser to HTML-encode special characters, preventing stored XSS attacks.

Example · js
const { body } = require('express-validator');

app.post('/comments', [
  body('text').trim().escape(), // converts < > & " ' to HTML entities
], (req, res) => {
  // req.body.text is safe to store and render
  res.status(201).json({ text: req.body.text });
});

Custom sanitiser middleware

Strips SQL LIKE wildcards and limits the search string to 100 characters before passing the query to the database.

Example · js
function sanitiseQuery(req, res, next) {
  if (req.query.q) {
    // Remove characters that could break a LIKE query
    req.query.q = req.query.q.replace(/[%_\\]/g, '').trim().slice(0, 100);
  }
  next();
}

app.get('/search', sanitiseQuery, (req, res) => {
  res.json({ query: req.query.q });
});

Discussion

  • Be the first to comment on this lesson.