Skip to main content
Middleware is the backbone of grammY. These types help you write type-safe middleware functions.

Middleware<C>

The main middleware type. Middleware can be either a function or an object containing middleware.
Usage:

MiddlewareFn<C>

A middleware function type.
Parameters:
  • ctx: The context object containing update information
  • next: Function to call the next middleware in the chain
Returns: Any value (typically 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.
Key points:
  • 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
Usage:

Common Mistake: Forgetting to await

MiddlewareObj<C>

An object that contains middleware.
This is how Composer and Bot instances work - they implement MiddlewareObj. Usage:

Specialized Middleware Types

grammY provides type aliases for common middleware patterns:

HearsMiddleware<C>

Middleware used with bot.hears():

CommandMiddleware<C>

Middleware used with bot.command():

CallbackQueryMiddleware<C>

Middleware used with bot.callbackQuery():

InlineQueryMiddleware<C>

Middleware used with bot.inlineQuery():

ChatTypeMiddleware<C, T>

Middleware used with bot.chatType():

ReactionMiddleware<C>

Middleware used with bot.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

  1. Always await next()
  2. Type your middleware
  3. Use specialized types
  4. Don’t call next() multiple times
Middleware types provide the foundation for building modular, type-safe bots with grammY!