Middleware and errors

Run shared code before routes, and handle errors in one place.

Middleware is a function that runs before your route. It can log, check a login, or stop the request. Order matters, as they run in the order you add them.

Node.js
function requireKey(req, res, next) {
  if (req.get("x-api-key") !== process.env.API_KEY) {
    return res.status(401).json({ error: "Not allowed" });
  }
  next();
}

app.get("/api/admin", requireKey, (req, res) => {
  res.json({ ok: true });
});

// Keep this last: it catches errors from the routes above.
app.use((err, req, res, next) => {
  console.error(err);
  res.status(500).json({ error: "Something went wrong" });
});

Send a plain message to the client and log the details on the server. Stack traces should never reach users.

โ† Your first Express APIDatabases and security โ†’