i18n
Your bot speaks the user’s language; your code shouldn’t have to keep saying
which one. The usual i18n pattern threads a lang argument from the handler
into every service and formatter that produces text — until half your
signatures carry it. Nestgram resolves the locale once per update and seeds
a translator into the same ambient AsyncLocalStorage rail that
sessions ride. From there, t() and locale() are free
functions you import and call anywhere in that update’s call chain. No
threading, no injection.
What I18nStage does per update
The reveal: t() works because of a built-in pipeline stage, not magic. The
dispatcher runs each update inside runAmbient(...) — a fresh
AsyncLocalStorage store. Before matching runs, I18nStage (order: 10,
ahead of sessions at 20) calls I18nService.resolve(ctx), which writes two
values into that store:
| Ambient key | Holds | Read by |
|---|---|---|
LOCALE | the resolved locale string | locale(), @Locale() |
TRANSLATE | I18nService.t itself | t(...) |
t() reads TRANSLATE out of the store at call time and calls it; if no store
is active (i18n off, or outside an update), it has nothing to read and returns
the key. So the free helper is a door onto I18nService.t, not a second
implementation of translation — the two cannot drift apart. That’s the whole
mechanism: I18nStage is a thin adapter over I18nService, discovered like any
user @UpdateStage. Nothing in the engine is privileged.
The honest trade-off: an ambient value is invisible in signatures, and
AsyncLocalStorage is in-process and per-call-chain — it does not survive
a queue or worker boundary. Both bite in specific places, and this page names
them.
Register the module
I18nModule.forRoot() takes your catalogs and a default locale. It’s a global
dynamic module — import it once, alongside NestgramModule:
import { Module } from '@nestjs/common';
import { join } from 'path';
import { I18nModule, NestgramModule } from 'nestgram';
@Module({
imports: [
NestgramModule.forRoot({
token: process.env.BOT_TOKEN ?? '',
polling: true,
}),
I18nModule.forRoot({
source: join(__dirname, 'locales'),
defaultLocale: 'en',
}),
],
})
export class AppModule {}Catalogs come from exactly one of three places. Configuring none — or two —
throws NestgramConfigError at boot, not at the first missed translation.
| Option | Catalog source | When |
|---|---|---|
source | a path to a locales/ folder, or your own TranslationSource | files on disk; a DB or remote service |
translations | an inline Translations object | a TypeScript map suits you better |
backend | a TranslatorBackend for another message format | plurals/selectors via Fluent (below) |
import { I18nModule, Translations } from 'nestgram';
const translations: Translations = {
en: { 'start.greeting': 'Hi, {name}!' },
uk: { 'start.greeting': 'Привіт, {name}!' },
};
I18nModule.forRoot({ translations, defaultLocale: 'en' });Locale files
Point source at a directory and you get one file per locale: the filename is
the locale, the extension picks the parser — en.json, uk.yaml, de.yml.
Keys nest naturally and flatten to dotted keys at load (list.empty); {name}
placeholders interpolate at translation time. An array value joins with
newlines — handy for multi-line help text. Other files in the directory are
ignored, but a directory that yields no catalog at all is a startup error rather
than a bot that silently answers in raw keys.
{
"menu": { "remind": "➕ Remind", "help": "ℹ️ Help" },
"start": { "greeting": "Hi, <b>{name}</b>!" },
"list": {
"empty": "No pending reminders 🎉",
"header": "You have <b>{count}</b> pending reminder(s):"
}
}menu:
remind: ➕ Нагадати
help: ℹ️ Допомога
start:
greeting: Привіт, <b>{name}</b>!
list:
empty: Немає нагадувань 🎉
header: 'У тебе <b>{count}</b> нагадувань:'
help:
text: # an array joins into one multi-line message
- <b>Бот-нагадувач</b> — пінгую, коли час.
- Надішли <code>10m Подзвонити мамі</code>.Use t() anywhere
Import t and call it — in the handler, or in any service the handler ends up
calling. No locale in sight, because both run inside the same update’s call
chain, and the chain shares one ambient store:
import { Injectable } from '@nestjs/common';
import { Command, Message, Router, Sender, t, User } from 'nestgram';
@Injectable()
export class ReminderService {
listText(pending: string[]): string {
return pending.length === 0
? t('list.empty')
: t('list.header', { count: pending.length });
}
}
@Router()
export class ReminderRouter {
constructor(private readonly reminders: ReminderService) {}
@Command('list')
list(message: Message) {
return this.reminders.listText([]);
}
@Command('remind')
remind(message: Message, @Sender() user: User) {
return t('start.greeting', { name: user.first_name });
}
}ReminderService knows nothing about Telegram, locales, or i18n config — it calls t() and gets text in the right language, because it runs inside the same update’s call chain that I18nStage seeded.
The second argument is interpolation params: {count} in the template becomes the value you pass. An unmatched placeholder stays visible in the output ({cuont} is a bug you can see), never silently blanked — only names the params object actually owns get replaced.
A key missing from every catalog never throws — it comes back visibly (the raw key, or in development a debug marker; see Spotting a missing key). A bot should still answer even when a translation is missing.
Need to render a different language inside the same update — a bilingual
confirmation, say? Pass an explicit locale as the last argument:
t('start.greeting', { name }, 'uk'). Like every form of t(), this one reads
the ambient store, so it works anywhere in the update’s call chain — but only
there. Outside an update, inject I18nService and call i18n.t(key, 'uk')
instead (the queue section covers it).
Spotting a missing key
In development, a missing key renders as a visible marker instead of silently
reading as its key — the key, then one name: value line per param the call
passed, so a miss with several params stays readable:
⟨cart.summary
items: 3
total: 42⟩A param-less miss is just ⟨cart.empty⟩. In production it falls back to the
bare key: never a throw, the bot always answers.
This is the devMode flag. It defaults to true only when NODE_ENV is
'development' — it fails closed, so an unset or misconfigured environment in
production never surfaces a marker to real users. A bare nest start doesn’t set
NODE_ENV, so pass devMode: true to see markers locally without it:
import { I18nModule } from 'nestgram';
import { join } from 'path';
I18nModule.forRoot({
source: join(__dirname, 'locales'),
defaultLocale: 'en',
devMode: true, // show markers locally even without NODE_ENV=development
});When you need the locale, not a translation
Sometimes you want the locale itself — picking a date format, logging, storing
a preference. @Locale() is sugar over the free locale(): the param
decorator reads LOCALE from the ambient store, the free function reads the
same value anywhere in the call chain.
import { Command, Locale, Message, Router } from 'nestgram';
@Router()
export class LangRouter {
@Command('lang')
lang(message: Message, @Locale() lang: string) {
return `Resolved locale: ${lang}`;
}
}With I18nModule configured the resolved locale is always a string (your
defaultLocale at worst). Without it, locale() returns undefined — like
everything here, it degrades instead of throwing.
Localized buttons that still route
A reply keyboard built from t() renders in the sender’s language — so the
button text that comes back differs per user, and a plain @Hears('➕ Remind')
only matches one of them. @HearsKey() is the i18n-aware @Hears: it matches a
message whose text equals the translation of a key in the current update’s
locale. I18nStage resolves the locale before matching runs, so this works as
routing, not as an afterthought.
import { Command, HearsKey, Message, ReplyKeyboard, Router, t } from 'nestgram';
const MENU = {
remind: 'menu.remind',
help: 'menu.help',
} as const;
@Router()
export class MenuRouter {
@Command('start')
start(message: Message) {
const keyboard = new ReplyKeyboard()
.text(t(MENU.remind))
.text(t(MENU.help))
.resize();
return message.answer(t('start.greeting'), { reply_markup: keyboard });
}
@HearsKey(MENU.remind)
remind() {
return t('remind.prompt');
}
@HearsKey(MENU.help)
help() {
return t('help.text');
}
}The same MENU.remind constant builds the button and routes the press — one
name, defined once, no per-locale predicates and no drifting literals.
How the locale is resolved
I18nService.resolve runs resolveLocale(ctx) per update, then keeps the
candidate only if a catalog actually exists for it:
| Step | What happens | Falls to |
|---|---|---|
| 1 | resolveLocale(ctx) runs — your custom resolver, or the default below | step 2 |
| 2 | candidate kept only if backend.hasLocale(candidate) — a de user with en/uk catalogs doesn’t get raw keys | defaultLocale |
| 3 | no candidate at all (channel posts have no sender; language_code is optional) | defaultLocale |
The default resolver is the sender’s Telegram language_code — what their
client reports. A custom resolver is just a synchronous function over the
update’s context:
import { I18nModule } from 'nestgram';
I18nModule.forRoot({
translations: { en: {}, uk: {} },
defaultLocale: 'en',
resolveLocale: (ctx) => {
const code = ctx.from?.language_code;
if (!code) {
return undefined; // → defaultLocale
}
const [base] = code.split('-'); // 'pt-br' → 'pt'
return base;
},
});Then, at translation time, each key falls back independently inside
I18nService: the resolved locale’s catalog → the fallbackLocale catalog
(defaults to defaultLocale) → the key itself. A half-translated catalog ships
usable — untranslated keys read in your fallback language instead of breaking.
Plurals and selectors: the Fluent backend
Flat catalogs with {name} interpolation cover most bots; plurals are where
they stop — “1 reminders” is the giveaway. For real plural rules (and other
in-message selectors) Nestgram ships a TranslatorBackend over
Fluent, Mozilla’s message format, reading .ftl
files:
pending = { $count ->
[one] You have { $count } pending reminder
*[other] You have { $count } pending reminders
}fluentDirectory is async — it lazily loads the parser and reads your files
once — so register it as the backend via forRootAsync:
import { join } from 'path';
import { I18nModule, fluentDirectory } from 'nestgram';
I18nModule.forRootAsync({
useFactory: async () => ({
backend: await fluentDirectory(join(__dirname, 'locales')),
defaultLocale: 'en',
}),
});Your calling code doesn’t change: t('pending', { count: 3 }). There’s also
fluentBackend({ en: enFtl, uk: ukFtl }) for inline .ftl strings.
Across a queue or worker boundary
The caveat the ambient rail forces you to respect: AsyncLocalStorage is
in-process and per-call-chain. A BullMQ job runs in a different call chain —
often a different process — where no ambient store exists, so t() returns the
key and locale() returns undefined. The framework doesn’t pretend
otherwise; you carry the locale explicitly. Capture it into the job payload when
you enqueue, and in the worker translate against it through I18nService, which
I18nModule exports for exactly this:
import { InjectQueue } from '@nestjs/bullmq';
import { Queue } from 'bullmq';
import { Command, Message, Router, locale } from 'nestgram';
@Router()
export class RemindRouter {
constructor(@InjectQueue('reminders') private readonly queue: Queue) {}
@Command('remind')
async remind(message: Message) {
// capture the ambient locale NOW — it won't survive into the worker
await this.queue.add('deliver', {
chatId: message.chat.id,
text: 'Buy milk',
locale: locale() ?? 'en',
});
return 'Scheduled.';
}
}import { Processor, WorkerHost } from '@nestjs/bullmq';
import { Job } from 'bullmq';
import { BotService, I18nService } from 'nestgram';
interface DeliverJob {
chatId: number;
text: string;
locale: string;
}
@Processor('reminders')
export class ReminderProcessor extends WorkerHost {
constructor(
private readonly bot: BotService,
private readonly i18n: I18nService,
) {
super();
}
async process(job: Job<DeliverJob>): Promise<void> {
// no ambient context here — translate against the carried locale instead
await this.bot.sendMessage(
job.data.chatId,
this.i18n.t('remind.delivered', { text: job.data.text }, job.data.locale),
);
}
}