Middleware and the Onion Model

Understand how Koa middleware executes, follow the onion model's execution order, and write practical middleware.

🎯 Introduction

By the end of this article, you will understand Koa's middleware execution order, explain how the onion model moves inward and then back outward, and write useful middleware for logging and response timing. The onion model is central to Koa and comes up often in interviews and application development.


🧱 What Does Koa Middleware Look Like?

Koa middleware is an async function that receives two arguments:

app.js
app.use(async (ctx, next) => {
    // On the way in: handle the request, for example by logging it
    await next(); // Pass control to downstream middleware
    // On the way out: perform cleanup or calculate elapsed time
});
  • ctx: The context object introduced in the previous article.
  • next: A function that runs the next middleware when called with await. Without the call, processing stops at the current middleware.

Express middleware also has next, but it passes control onward without the same awaited return flow. Koa's key difference is await next(): once all downstream middleware finishes, control returns here and execution continues. This is the basis of the onion model.


🧅 The Onion Model: Inward, Then Outward

Start with three middleware functions:

app.js
import Koa from 'koa';

const app = new Koa();

app.use(async (ctx, next) => {
    console.log('1 enter');
    await next();
    console.log('1 return');
});

app.use(async (ctx, next) => {
    console.log('2 enter');
    await next();
    console.log('2 return');
});

app.use(async (ctx) => {
    console.log('3 core handler');
    ctx.body = 'Hello';
});

app.listen(3000);

After one visit to http://localhost:3000, the terminal prints:

1 enter
2 enter
3 core handler
2 return
1 return

Think of middleware as layers of an onion. The request moves inward through layers 1 and 2 to reach the core application logic. Once processing finishes, control moves back outward through the same layers in reverse order. await next() is the step inward; the code after it runs on the way out.

       Request →
  ┌──────────────────┐
  │  Middleware 1    │
  │   ┌──────────┐   │
  │   │ Layer 2  │   │
  │   │  ┌────┐  │   │
  │   │  │Core│  │   │
  │   │  └────┘  │   │
  │   └──────────┘   │
  └──────────────────┘
       ← Response
Remember: first in, last out. The first middleware entered is the last to finish, just like a function call stack.

🛠 Practical Example: Response Timing

The onion model makes it natural to wrap the entire request flow with measurement code. A classic example is measuring how long each request takes to process.

app.js
import Koa from 'koa';

const app = new Koa();

// Response timing middleware
app.use(async (ctx, next) => {
    const start = Date.now(); // Record the start time on entry

    await next(); // Let downstream middleware run the application logic

    // On return: processing has finished, so calculate elapsed time
    const ms = Date.now() - start;
    ctx.set('X-Response-Time', `${ms}ms`);
    console.log(`${ctx.method} ${ctx.path} - ${ms}ms`);
});

// Application middleware
app.use(async (ctx) => {
    ctx.body = 'Hello Koa';
});

app.listen(3000);

After visiting the page, you will see a log such as GET / - 3ms in the terminal and an X-Response-Time header in the browser's response headers.

The useful part is that one await next() call wraps the entire application processing flow. Record start before it and calculate elapsed time after it to cover the request's lifecycle. Splitting the same work across separate request and response hooks would be less direct.


⚖️ How This Differs from Express Middleware

Express middleware follows a linear flow: middleware runs in sequence, and code after next() does not wait for downstream asynchronous work to finish. To measure response time in Express, you listen for the response's finish event, adding another step.

Koa uses async/await to support a wrapping execution model naturally. One await next() lets you perform work before and after downstream processing. Think of it this way: Express moves along a straight line, while Koa makes a round trip.

Two other differences to remember:

  • Write Koa middleware as an async function and use await before next() to preserve the intended execution order.
  • try/catch can catch asynchronous errors in Koa middleware, providing the basis for centralized error handling (covered later).
A common beginner mistake is omitting await from await next(). Without it, downstream middleware is not awaited, and the code intended to run on the way back executes at the wrong time. A bare next() in this pattern usually indicates a bug.

❓ Questions and Answers

Q1: What happens if middleware does not call next()?

Processing stops at that middleware, and downstream middleware does not run. The final middleware usually omits next() because it is the end of the chain.

Q2: Can code after next() modify ctx.body?

Yes. When await next() returns, application middleware has already set ctx.body. You can read or overwrite it here. Middleware that wraps responses in a consistent format uses this technique.

Q3: What determines middleware execution order?

The order of app.use() calls. Middleware registered first is entered first and returns last. Logging and error handling middleware therefore usually goes near the beginning.

Q4: Can middleware call next() more than once?

No. Each middleware may call next() only once. Calling it multiple times throws an error.


🧪 Practice

  1. Write logging middleware that prints [Request] GET /users on entry and [Response] 200 on return for each request.
app.js
import Koa from 'koa';

const app = new Koa();

app.use(async (ctx, next) => {
    // Write your code here
});

app.use(async (ctx) => {
    ctx.body = 'User list';
});

app.listen(3000);
  1. Deliberately remove await from await next() and observe how the terminal output order changes. Use this to understand why await is needed.

🎉 You now understand Koa's onion model! Next, we will add routing so different URLs can return different content.