Skip to content
Tutorials Center
My learning

Topics

Lesson 54 of 133 ยท Networking and HTTP

Middleware Pattern

Understand the middleware pattern in Node.js - the next() chain, error-handling middleware, async handlers, the onion model - and build a working mini Express in about 60 lines.

Almost every Node.js web framework is built around one idea: a request travels through a chain of small functions, each of which can inspect it, change it, answer it, or pass it on. These functions are called middleware. One middleware logs the request, the next one checks the login, another parses the JSON body, and finally a route handler writes the answer.

The pattern is simple enough that you can write the whole machinery yourself in about 60 lines. In this lesson you will do exactly that. First you will see the chain as plain functions, then connect it to a real http server, add error handling and async support, and finally look at the "onion" model used by Koa and Hono. Once you have built it, frameworks like Express stop being magic. For the underlying server API see The http Module: Servers; a router comes in Building a Router from Scratch.

The idea: a chain with next()

A middleware is a function that receives the request, the response and a function called next:

JavaScript
function middleware(req, res, next) {
  // look at req, maybe change it
  next(); // continue to the following middleware
}

Calling next() means "I am done, pass control on". Not calling it means "I handled it" (for example by sending a response) and the chain stops. The framework keeps a list of middleware and a position in it; next() moves the position forward and calls the next function. That is all.

Let us build this chain with ordinary objects instead of HTTP so you can focus on the control flow.

Node.js The chain without HTTP

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.

Look at the order of the log lines for /home: the "logger after" line appears only after the handler finished, because next() is a normal function call that returns when everything after it has run. Synchronous middleware therefore forms a stack, a fact we will use below. For /stop the third middleware never calls next(), so the handler never runs.

A mini Express in about 60 lines

Now connect the chain to http.createServer. We add three things people expect from Express:

  • app.use(fn) for middleware that runs on every request,
  • app.get(path, handler) / app.post(...) for route handlers that match method and path (with :param segments),
  • helper methods on the response: res.status(code), res.json(data), res.send(text).

Routes are just middleware that call next() when the method or path does not match. A final fallback produces a 404.

Node.js mini-express.mjs: a tiny Express clone

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 next. It is a closure over index, so every call advances through the same array. The fn.length check is the trick Express itself uses: a function that declares four parameters (err, req, res, next) is error-handling middleware. Express reads fn.length too, which is why you must write all four parameters even if you do not use next. The try/catch turns an exception thrown by a handler into next(thrown).

The real Express adds far more: sub-routers, app.use('/prefix', ...), req.get(), content negotiation helpers, view rendering and so on, but the core is the same loop you just wrote. See Express and Minimal Frameworks.

Typical middleware

With the machinery in place, real functionality is just more functions. Here are three that appear in nearly every app: a logger (that waits until the response is finished), authentication (stops the chain with 401), and a body parser (reads JSON and stores it on req.body, using what you learned in Request Bodies, JSON and Forms).

To keep the lesson readable, the examples below start from a compact version of the same framework core (without the route helper details you have already seen).

Node.js Logging, auth and a JSON body parser

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.

Order matters. The logger comes first so that it sees every request; the body parser comes before any route that needs req.body; authentication guards only paths under /admin. The unauthorised request was stopped by the auth middleware before the route ever saw it, and the logger still recorded it because it hooked the 'finish' event of the response. That is the standard way to log "after" something in plain callback-style middleware.

Note one subtle thing: the body parser is an async function. Our simple try/catch around fn(...) only catches synchronous throws; the promise an async function returns is ignored. A rejection inside it (say, from await) would become an unhandled rejection and the request would hang. The next section deals with that.

Error-handling middleware

When something fails, you do not want every handler to format its own error response. Instead, call next(error) (or throw), and let one error middleware at the end of the chain produce the response. The framework skips normal middleware and goes to the next function with four parameters.

For async code the framework must watch the returned promise. Express 5 does that automatically; Express 4 does not, and people wrote a wrapper like this:

Node.js Error middleware and async wrappers

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.

Three rules are visible here:

  1. Error middleware goes last and takes four parameters.
  2. Separate expected errors from bugs. HttpError means "tell the client", anything else is a bug that is logged in full and answered with a bland 500. Never put err.message or a stack trace of an unexpected error into the response, as the password in the message above shows. See Errors and Error Handling and Error Handling in Production.
  3. A thrown error inside async code is only caught if you attach .catch(next), which is what wrap does.

The onion model (Koa and Hono)

Express middleware runs "downwards": each function calls next() and usually returns. Koa and Hono make next() return a promise and use await next(), so a middleware can run code both before and after everything downstream finished. Because the order is "A before, B before, handler, B after, A after", it is called the onion model. It makes timing, response transformation and per-request transactions straightforward.

Node.js An async onion composer

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.

In the failing run, B after never executes because the exception skipped it, and the outer try/catch in A turned it into a 500. This is the biggest practical gain of the onion model: error handling is just try/catch around await next().

When to use middleware, and when not to

Middleware is excellent for cross-cutting concerns that apply to many routes: logging, authentication, parsing, rate limiting, CORS, compression and request-scoped context (see AsyncLocalStorage and Context). Keep these habits:

  • One job per middleware, named clearly, in an order you can read top to bottom.
  • Call next() exactly once, or send a response and return. Doing both causes "headers already sent" errors; the composer above even detects a second call.
  • Always return after sending a response inside a conditional, or code below it will still run.
  • Do not put business logic in middleware. It belongs in plain functions you can test without HTTP, as discussed in Project Structure and Architecture.
  • Watch the cost. Every request passes through every middleware; keep global middleware cheap and mount heavy ones only on the routes that need them.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens when a middleware neither calls next() nor sends a response?

    The chain stops and nobody finishes the response, so the client waits until some timeout closes the connection. Every path must either call next() or end the response.
  2. 2. How does Express recognise error-handling middleware?

    Express checks the function's length. Declaring four parameters marks it as error middleware, even if you do not use all of them.
  3. 3. Why is err.message of an unexpected error usually NOT sent to the client?

    Unexpected errors are bugs and may contain sensitive information. Log them for operators and return a generic 500 message.
  4. 4. In the onion model, where does ctx.body = ctx.body.toUpperCase() run relative to the handler when written after await next()?

    await next() waits for all downstream middleware and the handler. Code after it sees the finished result and can transform it.
  5. 5. A route handler is an async function that throws, and the framework does not watch promises. What is the fix used in the lesson?

    The wrapper calls .catch(next) on the returned promise, so rejections reach the error middleware like synchronous throws do.

Summary

  • Middleware are functions (req, res, next) run in order; next() passes control, and not calling it ends the chain.
  • A framework like Express is a loop over an array of functions with an index; you can write one in about 60 lines.
  • Routes are middleware that call next() when method or path do not match; a fallback at the end answers 404.
  • Error middleware has four parameters, sits last, logs unexpected errors and returns safe messages.
  • Async handlers need .catch(next) (Express 5 and most modern frameworks do it for you).
  • Koa and Hono use await next() so code can run before and after downstream work, giving simple try/catch error handling.
  • Keep middleware focused and ordered; keep business logic out of it.

Next: Designing REST APIs