Validating Input to an Express API

Share this video with your friends

Send Tweet

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:

  • Always assume query params and post bodies are undefined
  • Set defaults or check that they exist
  • When required values aren't found send a 400 status code and appropriate message
  • When you use urlencoded({ extended: true }) with express it tries to parse numbers and booleans into those primitives instead of strings, so be ready for that.
  • Always validate each value that is sent as input into your API, don't assume it's safe to use it without checking (see below for an example).

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!!