Nestgram v2.0
Docs/State, sessions & i18n

Conversations: the FSM

A single handler answers a single update. A registration flow needs more: ask the name, wait, ask the age, wait, save. Telegram won’t help you here — every message arrives as a fresh, contextless update, and “which question is this user answering?” is state you have to keep yourself.

Nestgram ships a finite state machine for exactly this (if you know aiogram’s FSM, you’ll feel at home). A conversation is in a state; the state narrows which handlers may fire; the handler stores the answer and moves the conversation on.

Mental model
message→snapshot loaded→@OnMessage(Reg.name)→fsm.set(Reg.age)

The mover behind the * is the FsmStage: a built-in dispatcher stage that, before matching runs, loads the conversation’s snapshot from the store onto the ambient AsyncLocalStorage rail. A state predicate and @Fsm() both read that one snapshot — routing and transitions share it.

Turn it on

Import FsmModule once, next to NestgramModule:

app.module.ts
import { Module } from '@nestjs/common';
import { NestgramModule, FsmModule } from 'nestgram';
import { RegistrationRouter } from './registration.router';

@Module({
  imports: [
    NestgramModule.forRoot({
      token: process.env.BOT_TOKEN ?? '',
      polling: true,
    }),
    FsmModule.forRoot(),
  ],
  providers: [RegistrationRouter],
})
export class AppModule {}

With no options it keeps state in a process-local MemoryStore — fine for development and single-instance bots; Where the state lives covers Redis. If you don’t import FsmModule at all, FSM is off: the FsmStage never runs, state predicates never match, and a transition throws instead of silently dropping a write.

Define the states

stateGroup() declares the steps of a flow — a factory, not a class, so the step ids infer cleanly in TS. Keep the shape of the data the flow collects right beside it:

registration.states.ts
import { stateGroup } from 'nestgram';

export const Reg = stateGroup('reg', ['name', 'age']);
// Reg.name.id === 'reg:name', Reg.age.id === 'reg:age'

export interface RegData {
  name: string;
}

Each member (Reg.name) is an FsmState, and it does double duty — FsmState implements RoutePredicate:

As…You write…What it does
an identityfsm.set(Reg.name)stores state: 'reg:name' on the snapshot
a route predicate@OnMessage(Reg.name)matches() returns currentStateId() === 'reg:name'

One definition drives both, so no 'reg:name' string lives in your handlers. Because the predicate reads the snapshot the FsmStage already loaded, it ANDs with the listener’s update type — @OnMessage(Reg.name) is “a message, and this user is in reg:name.”

The wizard

A complete two-step registration — name, then age, with a /cancel escape:

registration.router.ts
import {
  Router,
  Command,
  OnMessage,
  Message,
  Fsm,
  FsmContext,
  AnyState,
} from 'nestgram';
import { Reg, RegData } from './registration.states';

@Router()
export class RegistrationRouter {
  // Declared first: /cancel must win over the state steps below,
  // which would otherwise swallow it as plain input (first match wins).
  @Command('cancel')
  @AnyState()
  async cancel(message: Message, @Fsm() fsm: FsmContext) {
    await fsm.clear();
    return 'Cancelled.';
  }

  @Command('signup')
  async signup(message: Message, @Fsm() fsm: FsmContext<RegData>) {
    await fsm.set(Reg.name);
    return 'What should I call you?';
  }

  @OnMessage(Reg.name)
  async name(message: Message, @Fsm() fsm: FsmContext<RegData>) {
    if (!message.text) {
      return 'Text, please — what should I call you?';
    }
    await fsm.update({ name: message.text });
    await fsm.set(Reg.age);
    return `Nice to meet you, ${message.text}. How old are you?`;
  }

  @OnMessage(Reg.age)
  async age(message: Message, @Fsm() fsm: FsmContext<RegData>) {
    const age = Number(message.text);
    if (!Number.isInteger(age) || age <= 0) {
      return 'A number, please — how old are you?';
    }
    const { name } = fsm.data();
    await fsm.clear();
    return `Registered: ${name}, ${age}. Welcome aboard!`;
  }
}
1

@OnMessage(Reg.name) fires only while that user’s conversation is in reg:name. The state ANDs with the update type — and with any other predicates you pass alongside it.

2

@Fsm() injects the FsmContext it builds from the ambient snapshot. Type the collected data via the annotation — FsmContext<RegData> — since a decorator argument can’t set a parameter’s type.

3

fsm.update({ name }) merges an answer into the flow’s data; fsm.set(Reg.age) moves on. fsm.data() is Partial<RegData>, because a flow fills its fields step by step.

4

fsm.clear() finishes: state and data are dropped and the record is deleted from the store — an idle conversation stores nothing.

5

/cancel is declared first. First match wins, and the reg:name step matches any message — declared later, /cancel would be saved as somebody’s name.

A state step receives any message in that state — stickers and photos included — which is why name() checks message.text before trusting it. And notice what failed validation does in age(): it replies and doesn’t transition, so the user stays on the same step and tries again. That’s the whole retry mechanism — no special API.

The FsmContext surface

@Fsm() (and the fsm() free function) hand you the same stateless FsmContext — it reads the ambient snapshot on every call, so one shared instance serves every handler. Reads, then transitions:

MethodReturns / does
fsm.current()the current state id ('reg:name'), or null when idle
fsm.data()Partial<TData> gathered so far ({} when none)
fsm.set(state)enter a state — writes state through to the store
fsm.update(patch)merge a patch into the flow data, write through
fsm.setData(data)replace the flow data wholesale, write through
fsm.clear()drop state + data and delete the record

The two reads (current/data) degrade gracefully when FSM is unavailable; the four transitions throw. “Unavailable” and write-through spells out why.

Transitions are write-through

set, update, setData and clear persist the moment their await resolves — not at the end of the handler. There’s no deferred commit: each call writes the snapshot straight through to the store via the binding the FsmStage resolved (store.set(key, snapshot), or store.delete(key) for clear). So if sending the reply afterwards fails, the transition has still happened (aiogram behaves the same way). The flip side of the same coin: there is no rollback-on-throw. A flow stuck by a crash is exactly what the @AnyState() /cancel is for.

The context is also reachable outside handlers, as the fsm() free function — the same ambient bargain as t() in i18n, so a service deep in the call chain can transition the current conversation without you threading a context through every signature:

onboarding.service.ts
import { Injectable } from '@nestjs/common';
import { fsm } from 'nestgram';
import { Reg } from './registration.states';

@Injectable()
export class OnboardingService {
  async begin() {
    await fsm().set(Reg.name); // the current update's conversation
  }
}

Reads degrade gracefully when FSM is unavailable — fsm().current() returns null and fsm().data() returns {} — but a transition throws, because a silently dropped set is a debugging trap. “Unavailable” means FsmModule isn’t imported, or the update has no chat to scope a conversation to.

Idle or busy: @AnyState() and @NoState()

Two method-level modifiers cover the meta-conditions: @AnyState() fires only while some flow is active — the /cancel above works from any step of any flow — and @NoState() only while idle. The classic use for @NoState() is a catch-all that must not steal a wizard step’s input:

@OnMessage()
@NoState()
echo(message: Message) {
  return message.text; // never runs mid-wizard
}

Both are one-liners over the public @Match() primitive, which ANDs a predicate into every route a method declares — nothing privileged. @AnyState() is @Match(anyState), where anyState.matches() is currentStateId() !== null; @NoState() is its negation. The same @Match is yours for custom predicates, and you could rebuild @AnyState() yourself in three lines.

Where the state lives

Persistence is a KeyValueStore — three methods (get/set/delete), shared with sessions. The default is the in-process MemoryStore: state evaporates on restart and isn’t shared between instances, which is fine in development and honest about what it is. For production, hand FsmModule the Redis-backed store (named for sessions, but it’s just a KeyValueStore):

app.module.ts
import { FsmModule, RedisSessionStore } from 'nestgram';
import Redis from 'ioredis';

FsmModule.forRoot({
  // replaces the store's default 'nestgram:session:' prefix,
  // so FSM keys read nestgram:fsm:… instead of nestgram:session:fsm:…
  store: new RedisSessionStore(new Redis(), { prefix: 'nestgram:' }),
});

FSM records are namespaced fsm: inside the store, so pointing sessions and FSM at one store instance is safe — the two never collide. They stay separate facilities on purpose: a session is long-lived per-user data, FSM state is a position in a short dialogue plus its scratch answers. Finishing a flow shouldn’t wipe a user’s settings.

By default a “conversation” is scoped per chat + user (plus the forum topic and business connection when present, and the receiving bot in a multi-bot app): in a 1:1 chat that collapses to per-user, and in a group every member walks their own wizard independently. Override the key option to change that — return undefined to skip FSM for an update entirely:

FsmModule.forRoot({
  // one flow per chat — everyone in a group advances the same wizard
  key: (ctx) => (ctx.chat ? `chat:${ctx.chat.id}` : undefined),
});

Want the steps wired for you?

This core is deliberately low-level: explicit set calls, one handler per state. It’s transparent, but verbose for long flows. The Scenes layer sits on top of this same machinery and gives you ordered steps with @Scene / @Step / @OnEnter and a scene context that moves itself (next/back/goto) — reach for it when a flow grows past a couple of steps.