Skip to main content
Creating your own plugins allows you to encapsulate reusable functionality and share it across projects or with the community. This guide shows you how to build custom middleware and plugins using grammY’s powerful Composer API.

Understanding Middleware

At its core, a plugin is just middleware. Every middleware function receives two parameters:

Basic Plugin Structure

A simple plugin is a function that returns middleware:

Plugin with Configuration

Most plugins accept configuration options:

Adding Context Properties

Plugins often extend the context object with new properties or methods.

Defining a Context Flavor

Implementing the Plugin

Using the Flavored Plugin

Using the Composer Class

The Composer class lets you build complex middleware systems:

Middleware Object Pattern

Implement the MiddlewareObj interface for advanced plugins:

Real-World Example: Logger Plugin

Here’s a complete example of a logging plugin:

Real-World Example: Rate Limiter

A rate limiting plugin to prevent spam:

Real-World Example: Translation Plugin

A plugin that adds translation capabilities:

Advanced: Lazy Middleware

Create middleware that’s generated on-the-fly:

Advanced: Fork and Concurrency

Run middleware concurrently:

Advanced: Error Boundaries

Create safe plugin zones:

Advanced: Filter and Branch

Conditional middleware execution:

Testing Your Plugin

Always test your plugins:

Best Practices

  1. Type Safety - Always define context flavors for TypeScript support
  2. Configuration - Accept options to make plugins flexible
  3. Error Handling - Handle errors gracefully, don’t crash the bot
  4. Documentation - Document your plugin’s API and usage
  5. Testing - Write tests for your plugin logic
  6. Performance - Avoid blocking operations in middleware
  7. Composability - Make plugins work well with others
  8. Naming - Use clear, descriptive names for your plugins

Publishing Your Plugin

To share your plugin with the community:
  1. Create a separate npm package
  2. Use clear naming: grammy-plugin-name or @yourscope/grammy-plugin-name
  3. Include TypeScript types
  4. Write comprehensive documentation
  5. Add examples and tests
  6. Publish to npm

Example: Complete Plugin Template

Next Steps