Chapter 13: Custom Middleware in Lua

Write your own middleware functions. In this chapter, you will learn custom middleware in depth with Lua code examples, explanations, and best practices.

Overview

This chapter covers custom middleware for Kungfu.js developers using Lua. We will start with the basics, move through practical examples, and end with advanced techniques and common pitfalls.

Why This Matters

Understanding custom middleware is essential because it is a core part of building web applications. Every real-world app needs to handle write your own middleware functions. Skipping this chapter would leave a gap in your knowledge that would cause problems later.

Code Example

Here is how to use middleware in Lua:

// Custom middleware example
app.use((req, next) => {
    console.log(`['${req.method} ${req.path}']`);
    const response = next(req);
    response.headers['x-request-id'] = generateId();
    return response;
});

// Auth middleware (short-circuit)
app.use((req, next) => {
    if (req.path !== '/login' && !req.headers['authorization']) {
        return { status: 401, body: '{"error":"Unauthorized"}' };
    }
    return next(req);
});

The Onion Model

Middleware in Kungfu.js uses the "onion" model. Imagine an onion with layers. A request passes through each layer from outside to inside, then the response passes back through the same layers from inside to outside.

This means the first middleware you register runs first on the request (before the handler) and last on the response (after the handler). The last middleware runs last on the request and first on the response.

Common Mistakes

  • Not reading the documentation: Always check the API reference when something does not work as expected.
  • Skipping security: Never disable the default middleware unless you have a very good reason. Security is not optional.
  • Not testing: Write tests for your handlers. Kungfu.js makes this easy with the built-in test utilities.

Summary

In this chapter, you learned about custom middleware in Lua. You saw code examples, understood how things work under the hood, and learned about common mistakes to avoid.

What is Next?

In chapter 14, we will cover Middleware Execution Order: The onion model and how to control flow.