Chapter 14: Middleware Execution Order in Python
The onion model and how to control flow. In this chapter, you will learn middleware execution order in depth with Python code examples, explanations, and best practices.
Overview
This chapter covers middleware execution order for Kungfu.js developers using Python. We will start with the basics, move through practical examples, and end with advanced techniques and common pitfalls.
Why This Matters
Understanding middleware execution order is essential because it is a core part of building web applications. Every real-world app needs to handle the onion model and how to control flow. Skipping this chapter would leave a gap in your knowledge that would cause problems later.
Code Example
Here is how to use middleware in Python:
// 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 middleware execution order in Python. You saw code examples, understood how things work under the hood, and learned about common mistakes to avoid.
What is Next?
In chapter 15, we will cover Request Object Deep Dive: Headers, body, params, query all explained.