✨ Overview
@bymax-one/nest-notification is a transactional notification library for NestJS 11 that ships email, OTP (one-time passwords) and push channels behind a single dynamic module, plus a React subpath for the OTP input box.
Everything that touches the outside world — the email transport, the OTP store, the template renderer, the audit sink — is an interface you implement or pick from the bundled reference adapters. The same module runs on Resend or SMTP out of the box (or any provider you implement, SendGrid for example), on Redis or an in-memory map, with a Prisma audit log or none at all, without changing a single call site.
Why nest-notification?
- 🔌 Your database, your provider — The library defines the contracts (
IEmailProvider, IOtpStorage, IEmailTemplateRenderer, INotificationLogRepository). You supply the implementations. It never imports @prisma/client or any other ORM — a CI gate fails the build if one appears — so a cross-cutting concern never hard-wires your schema.
- 🏢 Multi-tenant from the first line — Every operation is scoped by
tenantId, store keys are sha256(sha256(tenantId):sha256(recipient)), and the audit interceptor resolves the trusted tenant from the request rather than the request body when you configure a resolver.
- 🔒 Native crypto only — Codes come from
crypto.randomInt and are compared with crypto.timingSafeEqual. No crypto-js, no otpauth, no uuid, no nanoid — the most security-sensitive path carries no third-party supply-chain risk.
- ⚛️ Atomic by construction — The attempt counter and the resend cooldown are mutated inside the storage (Redis Lua /
SET NX EX), never by a service-side read-then-write. A get + update pair races, and the race is exactly how a max-attempts ceiling gets bypassed under concurrent requests.
- 🪶 Pay for what you use —
"dependencies": {}. NestJS, your email SDK, your Redis client, and React are all peer dependencies, and only the channels you configure are registered in the container.
🔥 Features
📧 Email
- ✅ Pluggable transport —
IEmailProvider with a bundled ResendEmailProvider, an SmtpEmailProvider that speaks the protocol every relay and mail-capture server understands, and a NoOpEmailProvider for dev/test that logs a masked recipient only, never the body
- ✅ Template rendering —
IEmailTemplateRenderer with a bundled {{var}} renderer that HTML-escapes interpolated values in the HTML body
- ✅ Canonical template names —
CANONICAL_EMAIL_TEMPLATES so providers and templates agree on the wire
- ✅ Attachment guard — a configurable total size ceiling (10 MiB by default) rejected before the provider is called
🔢 OTP
- ✅ CSPRNG codes —
numeric / alpha / alphanumeric, built character by character from crypto.randomInt so every position is uniform
- ✅ TTL + max attempts — with the counter spent atomically inside the storage
- ✅ Atomic resend cooldown — acquired with
SET NX EX and released only on delivery failure, so two concurrent resends cannot both win
- ✅ Constant-time verification —
crypto.timingSafeEqual, never ===
- ✅ Per-purpose overrides — length, code type, TTL, attempts, and cooldown tuned per purpose (a password reset is not an email verification)
- ✅ Optional email delivery — hand the code to the email channel, or take it and deliver it yourself
🏢 Multi-Tenant & Audit
- ✅ SHA-256 storage keys —
sha256(sha256(tenantId):sha256(recipient)): no recipient PII in a key, and the encoding adds no ambiguity of its own, so two pairs never share one by construction
- ✅
tenantIdResolver — the audited tenant comes from a trusted source (a JWT claim, a subdomain, a gateway-checked header), not the payload
- ✅ Opt-in audit log — a fire-and-forget
INotificationLogRepository plus a NotificationAuditInterceptor; audit failures do not break delivery unless audit.swallowErrors is false
- ✅ This library never logs a code — not to a logger, an audit entry, or an error message it authors, enforced by a regression test. Text a provider authors has a documented ceiling: see Errors
🧩 Developer Experience
- ✅ Subpaths — server, zero-dependency shared types, React hooks, and a
testing storage contract
- ✅ Stable error catalog — namespaced codes shared byte-for-byte between server and frontend, so you localize on the
code
- ✅ Dual-format output — ESM + CJS + declarations for both, verified against the packed tarball on every PR
- ✅ Typed end to end — TypeScript
strict with exactOptionalPropertyTypes and noUncheckedIndexedAccess; zero any
📦 Subpath Exports
One package — import only what your app needs:
| Subpath |
Import |
Purpose |
Peer deps |
| Server |
@bymax-one/nest-notification |
NestJS module, services, providers, errors, tokens |
NestJS 11 (+ your provider/store SDKs) |
| Shared |
@bymax-one/nest-notification/shared |
Types + constants (error codes, TTLs) |
None |
| React |
@bymax-one/nest-notification/react |
useOtpInput + useOtpCountdown (UX/state only) |
React 19 |
| Testing |
@bymax-one/nest-notification/testing |
Executable IOtpStorage contract for your own storage |
None |
| Observability |
@bymax-one/nest-notification/observability |
Metrics, spans and a readiness check |
@bymax-one/nest-core, prom-client, @opentelemetry/api (all optional) |
| Push (Expo) |
@bymax-one/nest-notification/push |
ExpoPushProvider |
None |
| Push (FCM) |
@bymax-one/nest-notification/push/fcm |
FcmPushProvider |
None |
| Push (APNs) |
@bymax-one/nest-notification/push/apns |
ApnsPushProvider |
None |
shared (zero deps) ← server react
shared has no dependencies, server builds on it and re-exports its error codes and TTLs, and react imports nothing but react — importing one never drags in another's peers. Every subpath ships ESM (.mjs), CJS (.cjs), and declarations for both formats (.d.ts + .d.cts).
[!TIP]
Prefer to learn from a working app? See the nest-notification-example — a full NestJS project wired with this library.
🚀 Quick Start
1. Install
pnpm add @bymax-one/nest-notification
# Server subpath peers (required)
pnpm add @nestjs/common @nestjs/core reflect-metadata rxjs
# Pick your provider and store (optional peers): Resend or SMTP, plus Redis
pnpm add resend ioredis # …or: pnpm add nodemailer ioredis
# React subpath (optional)
pnpm add react
pnpm add -D @types/react # TypeScript projects: the hooks' declarations import React's types
[!NOTE]
Requires Node.js 24+ and NestJS 11. Every provider and storage SDK is an optional peer dependency: install only the ones your configuration names.
2. Development — NoOpEmailProvider + InMemoryOtpStorage
No external services. Emails are logged (a masked recipient only, never the subject or the body), and OTP state lives in process memory. Ideal for local dev and tests.
import { Module } from '@nestjs/common'
import {
BymaxNotificationModule,
NoOpEmailProvider,
InMemoryOtpStorage,
DefaultTemplateRenderer
} from '@bymax-one/nest-notification'
// The default renderer ships no templates: register the one the OTP email is rendered from.
const templateRenderer = new DefaultTemplateRenderer({
templates: {
'otp_code::en': {
subject: 'Your Acme verification code',
html: '<p>Your code is <strong>{{code}}</strong>. It expires in {{expiresInMinutes}} minutes.</p>',
text: 'Your code is {{code}}. It expires in {{expiresInMinutes}} minutes.'
}
}
})
@Module({
imports: [
BymaxNotificationModule.forRoot({
email: {
provider: new NoOpEmailProvider(),
defaultFrom: 'no-reply@dev.local',
templateRenderer
},
otp: {
storage: new InMemoryOtpStorage(),
defaultLength: 6,
defaultTtlSeconds: 600,
defaultMaxAttempts: 5,
resendCooldownSeconds: 60
}
})
]
})
export class AppModule {}
The OTP email is rendered from the otp_code template, and the default renderer ships none, so register one as above (the same template as in step 3). Without it the first generate() throws TEMPLATE_NOT_FOUND (its details carry a remedy for this case), and one warning, BYMAX_NOTIFICATION_OTP_TEMPLATE_NOT_RESOLVED, is logged at startup. Ignore that line if every generate() passes emailTemplate, if you deliver manually, or if your renderer loads its templates after startup.
Inject OtpService anywhere and the two-step flow is complete:
import { Injectable } from '@nestjs/common'
import { OtpService } from '@bymax-one/nest-notification'
@Injectable()
export class VerificationService {
constructor(private readonly otp: OtpService) {}
/** Generate + deliver an email-verification OTP. */
async start(tenantId: string, email: string): Promise<{ expiresAt: number }> {
const { expiresAt } = await this.otp.generate({
tenantId,
recipient: email,
purpose: 'email_verification',
deliverVia: 'email'
})
return { expiresAt }
}
/** Verify a submitted code. */
async confirm(tenantId: string, email: string, code: string): Promise<boolean> {
const result = await this.otp.verify({
tenantId,
recipient: email,
purpose: 'email_verification',
code
})
return result.valid
}
}
[!NOTE]
generate() returns only expiresAt and cooldownSeconds — never the code. Resolve the tenantId in your controller from a trusted source and pass it down; the service takes it as an explicit argument, so nothing is silently overridden.
3. Production — Resend + Redis
Real email via Resend and OTP state in Redis (keys are SHA-256 hashed). Wire your ioredis client however your app already does.
import { Module } from '@nestjs/common'
import Redis from 'ioredis'
import {
BymaxNotificationModule,
ResendEmailProvider,
RedisOtpStorage
} from '@bymax-one/nest-notification'
const redis = new Redis(process.env.REDIS_URL!)
@Module({
imports: [
BymaxNotificationModule.forRoot({
global: {
defaultLocale: 'en',
// Trust the tenant from a gateway-verified header, not the request body.
tenantIdResolver: (req) => String(req.headers['x-tenant-id'] ?? 'default')
},
email: {
provider: new ResendEmailProvider({ apiKey: process.env.RESEND_API_KEY! }),
defaultFrom: 'no-reply@acme.com',
defaultFromName: 'Acme',
templateRenderer // the DefaultTemplateRenderer from step 2, with its `otp_code` template
},
otp: {
storage: new RedisOtpStorage({ redisClient: redis }),
defaultLength: 6,
defaultCodeType: 'numeric',
defaultTtlSeconds: 600,
defaultMaxAttempts: 5,
resendCooldownSeconds: 60,
perPurpose: {
password_reset: {
length: 8,
codeType: 'alphanumeric',
ttlSeconds: 900,
maxAttempts: 5,
resendCooldownSeconds: 60
}
}
}
})
]
})
export class AppModule {}
ResendEmailProvider bounds every send with timeoutMs (default 15000, an integer from 1 to 2147483647), from the request to the end of the response body. A send that exceeds it fails with EMAIL_SEND_FAILED and the reason Resend request timed out after <n> ms. A timed-out send may still have been delivered: only the answer is missing, so do not treat the failure as proof the message was not sent. The library does not retry a failed send; an application that retries one (from a queue job, for example) should pass an idempotency key, which resend 6.x accepts as idempotencyKey, because the earlier attempt may already have been delivered.
For async configuration (e.g. reading secrets from ConfigService), use forRootAsync:
import { ConfigModule, ConfigService } from '@nestjs/config'
BymaxNotificationModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (config: ConfigService) => ({
email: {
provider: new ResendEmailProvider({ apiKey: config.getOrThrow('RESEND_API_KEY') }),
defaultFrom: config.getOrThrow('MAIL_FROM')
},
otp: { storage: new RedisOtpStorage({ redisClient: redis }) }
})
})
[!IMPORTANT]
forRootAsync supports the useFactory pattern. useClass / useExisting are not implemented and are rejected at startup.
4. SMTP — any relay, and end-to-end tests
SmtpEmailProvider drives any SMTP relay and the mail-capture servers (Mailpit, MailHog) that make email flows testable end to end. It needs the optional nodemailer peer.
import { SmtpEmailProvider } from '@bymax-one/nest-notification'
const relay = new SmtpEmailProvider({
host: process.env.SMTP_HOST,
port: 587,
credentials: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS }
})
[!WARNING]
STARTTLS is mandatory by default for any non-loopback host, because a network attacker can strip the plaintext STARTTLS capability and read the OTP body. Opt out only with requireTls: false. The option table, the TLS rationale and the header-injection guard are in docs/smtp-provider.md.
tls takes rejectUnauthorized, servername, ca, minVersion, maxVersion, ciphers, checkServerIdentity, cert, key, passphrase and pfx, and passes them to the transport as given; each value is checked when the provider is built (a boolean for rejectUnauthorized, a string for servername, ciphers and passphrase, one of TLSv1 to TLSv1.3 for the two version bounds, a string, a Buffer or an array of them for ca and cert, the same or, inside an array, Node's object carrying a passphrase ({ pem, passphrase }, { buf, passphrase }) for key and pfx, a function for checkServerIdentity), and a wrong type fails the build naming the key and the type but never the value; any other key fails when the provider is built, naming it, so a setting you asked for is forwarded or refused and never dropped.