Skip to main content
Sessions allow you to store data about users, groups, or chats that persists across multiple bot interactions. grammY provides a simple and powerful session middleware.

Basic Usage

The session plugin stores data per chat by default. Here’s a basic example:

Storage Adapters

By default, sessions are stored in memory. For production, use a storage adapter:
For production bots, consider using official storage adapters like @grammyjs/storage-mongodb, @grammyjs/storage-redis, or @grammyjs/storage-postgres.

Session Keys

By default, sessions are identified by chat ID. You can customize this:

Lazy Sessions

For better performance, use lazy sessions that only read when accessed:

Multi Sessions

Store different data types with separate keys:

Best Practices

Keep Sessions Small

Store only essential data. Large sessions impact performance.

Use Lazy Sessions

In high-traffic bots, use lazy sessions to avoid unnecessary database reads.

Implement Cleanup

Periodically clean up old sessions to save storage space.

Validate Data

Always validate session data—users can clear their data or migrate between chats.

Migration

Handle session schema changes:

See Also