Dereferencing request values before checking them

Dereferencing request values before checking them

Description

Reading a property or calling a method on a request value of null or undefined throws an exception.

Potential impact

Repeated failures can disrupt request handling. Error responses may also disclose internal details.

Remediation

Declare the required type, format and length in the request schema. Reject missing required values and use an appropriate default for optional values.

Examples

These routes use Express 5, where res.send(number) sends the number as JSON.

Before

javascript
app.get("/length", (req, res) => {
  const id = req.query.id;
  res.send(id.length);
});

After

javascript
app.get("/length", (req, res) => {
  const id = req.query.id;
  if (id == null) {
    return res.status(400).end();
  }
  res.send(id.length);
});

The revised route returns 400 when id == null, before reading its length. This checks presence only. Validate that id is an allowed string as well.

References