Skip to content

Sanitizing input in Express using express-validator

New Course Coming Soon:

Get Really Good at Git

You’ve seen how to validate input that comes from the outside world to your Express app.

There’s one thing you quickly learn when you run a public-facing server: never trust the input.

Even if you sanitize and make sure that people can’t enter weird things using client-side code, you’ll still be subject to people using tools (even just the browser devtools) to POST directly to your endpoints.

Or bots trying every possible combination of exploit known to humans.

What you need to do is sanitizing your input.

The express-validator package you already use to validate input can also conveniently used to perform sanitization.

Say you have a POST endpoint that accepts the name, email and age parameters:

const express = require('express')
const app = express()

app.use(express.json())

app.post('/form', (req, res) => {
  const name  = req.body.name
  const email = req.body.email
  const age   = req.body.age
})

You might validate it using:

const express = require('express')
const app = express()

app.use(express.json())

app.post('/form', [
  check('name').isLength({ min: 3 }),
  check('email').isEmail(),
  check('age').isNumeric()
], (req, res) => {
  const name  = req.body.name
  const email = req.body.email
  const age   = req.body.age
})

You can add sanitization by piping the sanitization methods after the validation ones:

app.post('/form', [
  check('name').isLength({ min: 3 }).trim().escape(),
  check('email').isEmail().normalizeEmail(),
  check('age').isNumeric().trim().escape()
], (req, res) => {
  //...
})

Here I used the methods:

Other sanitization methods:

Force conversion to a format:

Like with custom validators, you can create a custom sanitizer.

In the callback function you just return the sanitized value:

const sanitizeValue = value => {
  //sanitize...
}

app.post('/form', [
  check('value').customSanitizer(value => {
    return sanitizeValue(value)
  }),
], (req, res) => {
  const value  = req.body.value
})
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my Express.js Handbook
→ Read my Express.js Tutorial on The Valley of Code

Here is how can I help you: