What is Middleware?
In simple terms, middleware is just a fancy word for a listener. When you write:The Middleware Signature
Middleware functions have this signature:Context
The context object containing the update and API methods
NextFunction
A function that invokes the next middleware in the chain
Example Middleware
The next Function
The next function is crucial to understanding middleware. It:
- Passes control to the next middleware in the chain
- Returns a
Promisethat resolves when downstream middleware completes - Allows you to run code both before and after downstream middleware
Middleware Chain
Middleware executes in the order it’s registered:next(), the chain stops:
Registering Middleware
bot.use() - Universal Middleware
Runs for all updates:
bot.on() - Filtered Middleware
Runs only for specific update types:
bot.command() - Command Middleware
bot.hears() - Text Matching
bot.callbackQuery() - Callback Query Handling
Other Specialized Methods
The Composer Class
TheBot class extends Composer, which provides all middleware registration methods. You can use Composer independently for modular code:
Advanced Middleware Patterns
Conditional Execution with filter()
Run middleware only when a custom condition is met:
Excluding Updates with drop()
Skip middleware for certain updates:
Branching with branch()
Choose between two middleware paths:
Routing with route()
Route to different handlers based on a value:
Lazy Middleware with lazy()
Generate middleware dynamically per update:
Concurrent Middleware with fork()
Run middleware concurrently to the main stack:
Error Boundaries
Catch errors in specific middleware subtrees:Middleware Objects
Middleware can be packaged as objects:Middleware Composition
You can chain middleware registration:Composer instance:
Running Middleware Manually
Run middleware with therun() function:
Best Practices
Middleware Flow Diagram
Type Safety
Middleware is fully typed:Related
- Context - Understanding context objects
- Filter Queries - Filtering updates
- Error Handling - Handling errors in middleware
- Bot - The Bot class