Whenever you're designing an API that receives input, there's a chance people are going to use it maliciously or incorrectly.
This lesson will look at some common problems that can occur when we assume input exists that doesn't and how to pro-actively handle it by sending status code 400 Bad Request
with custom response messages. A popular library for input validation is Joi.
A few notes:
undefined
400
status code and appropriate messageurlencoded({ extended: true })
with express it tries to parse numbers and booleans into those primitives instead of strings, so be ready for that.One simple strategy for validating input is to put the correct values in an Array or Set:
const { sort = "desc" } = req.query;
const validSorts = new Set(["desc", "asc"]);
if (!validSorts.has(sort)) {
return res.status(400).send("Invalid Sort Param");
}
One of the worst things you can do in your express app is forget to return
when you call res.send()
. It leads to this dreaded Error: Can't set headers after they are sent to the client
error which can be very hard to trace.
Another important concept is to never ever ever blindly pass in the results of req.query
or req.body
to some other object. It's potentially a massive security vulnerability. Imagine a scenario like this:
** DO THIS **
const { squareFootage, numRooms} = req.body
const house = new House({ squareFootage, numRooms})
DO NOT DO THIS
const body = req.body // someone could pass in price: 0
const house = new House(body) // free house for me!!