Sanitizing input in Express using express-validator
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:
trim()trims characters (whitespace by default) at the beginning and at the end of a stringescape()replaces<,>,&,',"and/with their corresponding HTML entitiesnormalizeEmail()canonicalizes an email address. Accepts several options to lowercase email addresses or subaddresses (e.g.flavio+newsletters@gmail.com)
Other sanitization methods:
blacklist()remove characters that appear in the blacklistwhitelist()remove characters that do not appear in the whitelistunescape()replaces HTML encoded entities with<,>,&,',"and/ltrim()like trim(), but only trims characters at the start of the stringrtrim()like trim(), but only trims characters at the end of the stringstripLow()remove ASCII control characters, which are normally invisible
Force conversion to a format:
toBoolean()convert the input string to a boolean. Everything except for ‘0’, ‘false’ and ” returns true. In strict mode only ‘1’ and ‘true’ return truetoDate()convert the input string to a date, or null if the input is not a datetoFloat()convert the input string to a float, or NaN if the input is not a floattoInt()convert the input string to an integer, or NaN if the input is not an integer
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
}) download all my books for free
- javascript handbook
- typescript handbook
- css handbook
- node.js handbook
- astro handbook
- html handbook
- next.js pages router handbook
- alpine.js handbook
- htmx handbook
- react handbook
- sql handbook
- git cheat sheet
- laravel handbook
- express handbook
- swift handbook
- go handbook
- php handbook
- python handbook
- cli handbook
- c handbook
subscribe to my newsletter to get them
Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing flavio@flaviocopes.com. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.