Chapter 12: Built-in Middleware in TypeScript
Security headers, CORS, rate limiting, logging. In this chapter, you will learn built-in middleware in depth with TypeScript code examples, explanations, and best practices.
Overview
This chapter covers built-in middleware for Kungfu.js developers using TypeScript. We will start with the basics, move through practical examples, and end with advanced techniques and common pitfalls.
Why This Matters
Understanding built-in middleware is essential because it is a core part of building web applications. Every real-world app needs to handle security headers, cors, rate limiting, logging. Skipping this chapter would leave a gap in your knowledge that would cause problems later.
Code Example
Here is how to use middleware in TypeScript:
// 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 built-in middleware in TypeScript. You saw code examples, understood how things work under the hood, and learned about common mistakes to avoid.
What is Next?
In chapter 13, we will cover Custom Middleware: Write your own middleware functions.