Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 39 ยท Building an API

Middleware and Error Handling

Build a middleware pipeline for a REST API: logging, request ids, CORS, body parsing, auth guards, async errors, a central error handler and a 404 fallback.

Some work has to happen for every request: log it, give it an id, check CORS, parse the body, verify a token, catch errors. Copy-pasting that into each handler is how bugs multiply. Middleware solves this: a chain of small functions, each of which can inspect or change the request, produce a response or pass control to the next function.

The idea is the same in Express, Koa, Laravel, ASP.NET Core and Django. In this lesson you build a pipeline yourself with about twenty lines of code, then use it for the most important job: handling errors in one place.

The middleware pattern

A middleware is a function (ctx, next). Calling await next() continues down the chain; not calling it stops the request right there (for example when authentication fails). Code after await next() runs on the way back, which is how timing and logging wrap the handler.

flowchart LR
    A["Request"] --> B["requestId"] --> C["logger"] --> D["CORS"] --> E["auth guard"] --> F["body parser"] --> G["route handler"]
    G -. "response travels back" .-> A

Each layer can act before the handler, after it, or end the request early.

The order matters. Request ids come first so every later log line can use them. The error handler wraps every layer that can fail, so it sits right after the request id and the logger: those two then still see the final status of error responses too. Authentication runs before the body parser, so you do not parse megabytes of JSON from someone who may not use the API.

A tiny compose

JavaScript
function compose(middleware) {
  return function run(ctx) {
    let index = -1;
    function dispatch(i) {
      if (i <= index) throw new Error('next() called twice');
      index = i;
      const fn = middleware[i];
      if (!fn) return Promise.resolve();
      return Promise.resolve(fn(ctx, () => dispatch(i + 1)));
    }
    return dispatch(0);
  };
}

dispatch(i) calls middleware i and hands it a next that calls middleware i + 1. Wrapping everything in a Promise means both sync and async middleware work, and a thrown error becomes a rejected promise that bubbles outward to the error handler.

Node.js Middleware order: the onion

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

For /public the layers run down and then back up in reverse order. For /private the auth layer returns without calling next(), so the handler and the body parser are never reached.

A central error handler

Without a central place, every handler needs its own try/catch, and the responses drift apart. Make the first layer after the request id and logger the error boundary:

  1. await next() inside try.
  2. If it throws an expected error (HttpError with a status), convert it into the matching problem response.
  3. If it throws anything else, log it with the request id and respond with a generic 500.

Also add a fallback at the end of the chain for unmatched routes, so unknown URLs get your normal JSON 404 rather than a framework default page.

Beware of asynchronous code that escapes the chain: a promise that rejects with nobody awaiting it (setTimeout(() => { throw ... }) or a forgotten await) will not reach your error handler. Always await your async work, and register process-level handlers (unhandledRejection) as a last line of defence that logs and exits.

A complete pipeline on a real server

The server below uses compose for a full stack: request id, access log, a small CORS layer, error boundary, an API-key guard for /admin and a JSON body parser. Routes are inline for brevity.

Node.js A real pipeline with an error boundary

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Study three things in the output. The 500 for /bug shows only a generic body; the real message appears just in the server log. Every response, success or error, carries a Request-Id and appears in the access log with its final status, because the logger wraps next(). The 401 came from a thrown HttpError, so the guard did not need to know how to format a response.

Common middleware you will use

Middleware Job
Request id Tags each request for logs and error bodies
Access log Method, path, status, duration
CORS Allows browser clients from specific origins
Body parser Reads and limits JSON, form or multipart bodies
Authentication Identifies the caller from a token or session
Authorization Checks permissions for the route
Rate limiting Stops abusive clients (see the security chapter)
Compression gzip or brotli responses
Error handler Converts errors into consistent responses

In frameworks such as Express you write the same functions as (req, res, next) and register them with app.use(...). The concept is identical, only the context object differs.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens if a middleware does not call next()?

    Not calling next() ends the chain. That is how guards reject requests early.
  2. 2. Why does the error-handling middleware wrap all the layers that can fail?

    Wrapping the rest of the chain in try/catch means every thrown error is handled in one place.
  3. 3. Why should an authentication guard run before the body parser?

    Cheap rejections first; expensive work only for permitted callers.
  4. 4. A promise rejects after the handler already finished and nobody awaited it. Will the error middleware see it?

    Errors outside the awaited chain escape the try/catch, which is why every async call must be awaited.

Summary

  • Middleware are small (ctx, next) functions that run before and after handlers; order matters.
  • A guard stops the chain by not calling next().
  • Put one error boundary in front of every layer that can fail: expected HttpErrors become precise responses, anything else becomes a logged, generic 500.
  • Add request ids, access logs, CORS and body parsing as layers, and a JSON 404 fallback.
  • Always await async work so errors travel through the chain.

Next: Authentication vs Authorization