Middleware<C>
The main middleware type. Middleware can be either a function or an object containing middleware.MiddlewareFn<C>
A middleware function type.ctx: The context object containing update informationnext: Function to call the next middleware in the chain
void or Promise<void>)
Usage:
Middleware Execution Flow
Middleware executes in the order it’s registered:NextFunction
The function passed to middleware for calling downstream middleware.- Always returns a
Promise - Should be
awaited to ensure proper execution order - Calling it passes control to the next middleware
- Not calling it stops the middleware chain
Common Mistake: Forgetting to await
MiddlewareObj<C>
An object that contains middleware.Composer and Bot instances work - they implement MiddlewareObj.
Usage:
Specialized Middleware Types
grammY provides type aliases for common middleware patterns:HearsMiddleware<C>
Middleware used withbot.hears():
CommandMiddleware<C>
Middleware used withbot.command():
CallbackQueryMiddleware<C>
Middleware used withbot.callbackQuery():
InlineQueryMiddleware<C>
Middleware used withbot.inlineQuery():
ChatTypeMiddleware<C, T>
Middleware used withbot.chatType():
ReactionMiddleware<C>
Middleware used withbot.reaction():
Custom Context Types
All middleware types are generic over the context type:Composing Middleware
Create reusable middleware compositions:Error Handling
Middleware can throw errors. Use error boundaries:Advanced: run() Function
Manually execute middleware:Best Practices
-
Always await next()
-
Type your middleware
-
Use specialized types
-
Don’t call next() multiple times