Skip to content

Notifications & mail ​

Tell a user something happened — "invoice paid", "new comment", "subscription expiring" — once, and deliver it across every channel they've opted into: email, an in-app bell, SMS, WhatsApp. @basaltkit/notifications validates the payload, respects per-recipient preferences, and reports what was sent, skipped or failed — one channel failing never blocks the others. @basaltkit/mailer is the email engine underneath (and works standalone): typed mails, injection-safe HTML templating, and swappable drivers.

Mental model ​

Two layers, one direction of dependency:

LayerPackageJob
Notifier@basaltkit/notificationsOne event → many channels (mail, inApp, sms, whatsapp, custom), with per-recipient preferences and a delivery report
Mailer@basaltkit/mailerOne typed mail → one driver (SMTP, Resend, SES, Mailgun, log, memory), with safe HTML templating and header-injection guards

The mail channel bridges the two: when mailerPlugin is registered, the notifier delivers mail through it automatically. Use the mailer directly for transactional flows that aren't "notifications" (password reset, magic links). @basaltkit/mailer is a peer of @basaltkit/notifications (since 2.0), so both read the same MAILER binding: install it in the app (pnpm add @basaltkit/notifications @basaltkit/mailer).

Define a notification ​

Describe it once: the data (a Zod schema), the channels, and how each channel presents it.

ts
import { defineNotification } from '@basaltkit/notifications'
import { z } from 'zod'

export const InvoicePaid = defineNotification({
  name: 'invoice.paid',
  schema: z.object({ amount: z.number(), number: z.string() }),
  channels: ['mail', 'inApp'],
  via: {
    mail: (d) => ({ subject: `Invoice ${d.number} paid`, text: `We received ${d.amount}.` }),
    inApp: (d) => ({ title: 'Invoice paid', body: `${d.number} — ${d.amount}` }),
  },
})

channels may also be a function (recipient, data) => string[] for dynamic routing. Each via.<channel> renderer returns the channel's message shape — { subject, text?, html? } for mail, { title, body?, data? } for in-app, { body } for sms/whatsapp. A definition may also set defaults and mandatory per channel — see Default-off and mandatory channels.

Register and send ​

ts
import { notificationsPlugin, NOTIFIER } from '@basaltkit/notifications'
import { mailerPlugin } from '@basaltkit/mailer'

app.use(mailerPlugin({ /* … */ })) // the mail channel wires itself when a mailer is present
app.use(notificationsPlugin())      // the inApp channel is on by default

const report = await container.get(NOTIFIER).notify(recipient, InvoicePaid, { amount: 90, number: 'A-1' })
// { sent: [{ channel: 'mail' }, { channel: 'inApp' }], failed: [], skipped: [] }

The recipient comes first, then the definition, then the data. It is any { id, email?, phone?, channelPreferences? } object. Turn a channel off per recipient with channelPreferences ({ sms: false }) — disabled channels appear in skipped. A channel that throws lands in failed (with the error) and emits the notification:failed hook; successful deliveries emit notification:sent.

The mailer ​

Typed mails ​

A mail is defined once — name, schema, and renderers — then sent with validated data and an envelope:

ts
import { defineMail, html, MAILER } from '@basaltkit/mailer'
import { z } from 'zod'

export const WelcomeEmail = defineMail({
  name: 'welcome',
  schema: z.object({ name: z.string() }),
  subject: ({ name }) => `Welcome, ${name}!`,
  text: ({ name }) => `Hello ${name}`,
  html: ({ name }) => html`<h1>Hello ${name}</h1>`,
})

await container.get(MAILER).send(WelcomeEmail, { name: 'Ada' }, { to: 'ada@acme.io' })

Invalid data throws MailValidationError before anything is sent. The envelope is { to, from?, cc?, bcc?, replyTo? }; a missing to or from (after the plugin's default) throws MailIncompleteError.

Injection-safe HTML — html ``, raw(), escapeHtml() ​

Mail bodies are usually rendered from user-controlled data (names, titles, comments). Interpolating it bare hands an attacker markup inside mail sent from your own DKIM/SPF-aligned domain — phishing content, tracking pixels, XSS in permissive webmail clients. The safe path is the default path: write bodies with the html `` tagged template and every interpolation is escaped automatically — remembering to escape is not required, forgetting is not possible.

ts
import { html, raw, escapeHtml } from '@basaltkit/mailer'

html`<p>Hi ${userName}</p>`            // userName is escaped — always safe
html`<div>${html`<b>${inner}</b>`}</div>` // nested templates compose, no double-escaping
html`<ul>${items.map((i) => html`<li>${i}</li>`)}</ul>` // arrays render item-by-item
raw('<hr>')                             // trusted markup you wrote — passes through verbatim
escapeHtml(value)                       // manual escaping for hand-built strings

html returns a SafeHtml that stringifies to its markup — drop it straight into a mail's html field. Only ever pass your own markup to raw(), never user input.

Header-injection choke point ​

Every resolved message passes through the exported assertHeaderSafe(message) before it reaches any driver (and again after a queue round-trip): a CR/LF in the subject or a malformed address in from/to/cc/bcc/replyTo — the classic \r\nBcc: evil@x.com vector — throws MailHeaderInjectionError (MAIL_HEADER_INJECTION, HTTP status 400). You don't call it yourself; it's the single assembly choke point, so every driver is protected, not just SMTP.

Drivers ​

Driverdriver:NeedsNotes
Log'log' (default)—Prints to a sink (default console.log). Redacts bodies in production — see below
Memory'memory'—Captures messages in-process — for tests
SMTP'smtp'smtp: { … }Any SMTP relay
Resend'resend'resend: { … }HTTP API
SES'ses'ses: { … }AWS SES API
Mailgun'mailgun'mailgun: { … }HTTP API

An unrecognized driver string throws at boot — it does not silently fall back to the log driver, because that would print every outbound mail (reset links included) to stdout in a deploy that only typo'd a config value.

The log driver redacts bodies in production

Unless NODE_ENV is explicitly development or test (so also with it unset or staging), LogMailDriver replaces the body with (body redacted in production — …) — mail bodies routinely carry password-reset links, magic links and tokens, which must not be retained by a log aggregator just because a deploy was left on the default driver. Dev and test are unchanged, so your magic links still print locally. Opt back in explicitly with logBody: true.

Layout, tenant sender, queue, preview ​

ts
import { mailerPlugin, tenantFrom } from '@basaltkit/mailer'
import { smtpMailer } from '@basaltkit/mailer-smtp'

mailerPlugin({
  driver: smtpMailer({ url: process.env.SMTP_URL! }),
  from: tenantFrom('noreply@acme.io'),  // reads ctx().tenant.mailFrom, else the fallback
  layout: (body, { mail }) => `<!doctype html><body>${body}</body>`, // shared branding wrapper
})
  • layout wraps every HTML body (branding/header/footer); read ctx().tenant inside for per-tenant branding. Any template engine (MJML, React Email, Handlebars…) can render inside layout or a mail's own html().
  • Queue — mailer.useQueue((m) => SendMail.dispatch(m)) hands resolved messages to a @basaltkit/queue job whose handler calls mailer.deliver(m).
  • Preview — declare previews: [...] and run basalt mail:preview for a browser dev server that renders each mail with sample data through the real schema validation and layout.

Receiving mail (inbound) ​

The mailer only sends. Receiving is a separate package, @basaltkit/inbound-mail: a relay (Cloudflare Email Routing, an IMAP poller, your own MTA) posts each message as signed raw bytes, inboundMailRoutes() verifies them and routes by the signed recipient, and parseInbound() parses within limits and trusts Authentication-Results only from servers you list. Never decode the message to a string before verifying it: a message that is not valid UTF-8 would no longer match its signature.

For a provider that posts its own format (Postmark, SendGrid Inbound Parse, Mailgun routes, SES → SNS), put it behind a relay that signs the wire format, or receive it yourself on a rawBody() route and verify the bytes with verifySignature(header, body.bytes, secret).

SMS & WhatsApp ​

Deliver over a provider-agnostic SmsSender — implement one method over Twilio, Vonage, MessageBird, AppyPay… and the framework depends on no provider SDK.

ts
import { SmsChannel, whatsappChannel, notificationsPlugin } from '@basaltkit/notifications'
import type { SmsSender } from '@basaltkit/notifications'

const twilio: SmsSender = {
  async send({ to, from, body }) {
    await twilioClient.messages.create({ to, from, body })
  },
}

app.use(notificationsPlugin({
  channels: [
    new SmsChannel(twilio, { from: '+15551234567' }),          // channel 'sms'
    whatsappChannel(twilio, { from: 'whatsapp:+15551234567' }), // channel 'whatsapp'
  ],
}))

The address comes from recipient.phone (whatsappChannel prefers recipient.whatsapp ?? recipient.phone). Point the notification's via.sms / via.whatsapp at a { body } message:

ts
const LowBalance = defineNotification({
  name: 'wallet.low',
  channels: ['sms', 'inApp'],
  via: {
    sms: (d) => ({ body: `Balance ${d.amount}. Top up to keep sending.` }),
    inApp: (d) => ({ title: 'Low balance' }),
  },
})

Both channels honour channelPreferences opt-out like every channel, and a recipient with no phone number surfaces in failed without blocking the others.

Preferences & digests ​

For durable, per-notification × channel opt-out, add a PreferenceStore (notificationsPlugin({ preferences })) — the most-specific rule wins. In production use a durable one: sqliteInAppStore(path).preferences from @basaltkit/notifications-sqlite, or prismaPreferenceStore(prisma) from @basaltkit/notifications-prisma (the NotificationPreference model is in its bundled schema). To batch low-priority notifications into a periodic summary, collect them into a Digest and flush() on a schedule. See the package reference for the full API.

Default-off and mandatory channels ​

A definition can change the default per channel, and exempt channels from opting out:

ts
export const WeeklyDigest = defineNotification({
  name: 'digest.weekly',
  channels: ['mail', 'sms'],
  via: { /* … */ },
  defaults: { sms: false }, // opt-in: only users who turned SMS on get it
})

export const PasswordChanged = defineNotification({
  name: 'security.password-changed',
  channels: ['mail', 'inApp'],
  via: { /* … */ },
  mandatory: ['mail'], // cannot be silenced
})

The notifier decides each channel in this order: a mandatory channel is always sent; an inline channelPreferences: { x: false } mutes it; otherwise the most specific stored preference decides; then an inline true; and only when the recipient stated nothing does defaults[channel] (default true) apply. NotificationPreferences.preference() is that stored-preference step: it returns the most specific match's enabled, or undefined when nothing matches.

preference() is the only extension point. For quiet hours, compliance blocks or plan gating, subclass NotificationPreferences and override it — return false to block, true to send, undefined to let defaults decide; mandatory channels still bypass it:

ts
class QuietHours extends NotificationPreferences {
  override async preference(userId: string, notification: string, channel: string) {
    if (channel === 'sms' && isNight(userId)) return false
    return super.preference(userId, notification, channel)
  }
}

allowed() was removed in @basaltkit/notifications 2.0. A preferences object that still defines it (a 1.x override) makes new Notifier() throw LegacyAllowedOverrideError (NOTIFICATION_ALLOWED_OVERRIDE_REMOVED) instead of silently ignoring the logic: move it into preference(). Code that calledallowed() to ask "may I send?" can use (await prefs.preference(userId, notification, channel)) ?? true.

The in-app inbox ​

inAppRoutes() serves the bell for the signed-in user — the recipient is always the session, never a parameter:

RouteWhat
GET /me/notificationsList (?unreadOnly, ?limit ≤ 100, default 30)
GET /me/notifications/unread-count{ count }
POST /me/notifications/:id/readMark one read (404 for anyone else's)
POST /me/notifications/read-allMark all read → { marked }
ts
fastifyPlugin({ routes: [...inAppRoutes({ meta: { rateLimit: { max: 60 } } })] })

meta is merged into every route; auth: true is always applied on top. read-all marks every unread notification: in one statement on a store with markAllRead (memory, SQLite, Prisma), or page by page on an older custom store — it used to stop after the first 100.

Grouping ​

Give the in-app message a groupKey to collapse repeats into one row while it is unread — "3 new comments on Contract 12" instead of three rows:

ts
via: {
  inApp: (d) => ({ title: `${d.author} commented`, groupKey: `doc:${d.docId}:comments` }),
}

The unread row's count goes up and it takes the latest title, body and data; once it is read, the next one starts a new row. Needs a store with upsertGroup (memory, SQLite, Prisma — the Prisma schema gained the optional groupKey/count columns); a custom store without it appends a row per notification.

Retention ​

Inboxes grow forever unless something deletes them. Stores with prune delete read rows older than readBefore and unread rows older than unreadBefore (epoch ms, across all recipients). Run it from the scheduler:

ts
schedulerPlugin({
  define: (schedule) => {
    schedule.call('notifications:prune', async () => {
      const day = 86_400_000
      await app.container.get(IN_APP).prune?.({
        readBefore: Date.now() - 30 * day,
        unreadBefore: Date.now() - 180 * day,
      })
    }).daily().at('04:00')
  },
})

Options reference ​

notificationsPlugin(options) ​

OptionTypeDefaultWhy
channelsNotificationChannel[][]Extra channel drivers (sms, push, whatsapp, custom) beyond the built-in inApp/mail
inAppInAppStore | falsein-memory storePersist the in-app bell; false disables the channel entirely
preferencesPreferenceStore | trueoffDurable per-user opt-outs; true uses an in-memory store (dev)
digestDigestStore | trueoffBatch low-priority notifications for periodic flushing

mailerPlugin(options) ​

OptionTypeDefaultWhy
driver'smtp' | 'log' | 'memory' | 'resend' | 'ses' | 'mailgun''log'Which transport sends. An unknown string throws at boot (no silent log fallback)
smtp / resend / ses / mailgundriver options—Required by the matching driver
fromstring | (() => string | undefined)—Default sender; a function resolves per send (tenantFrom() for tenant branding)
replyTostring—Default reply-to
layout(html, { mail, data }) => stringnoneShared HTML wrapper applied to every HTML body
sink(line: string) => voidconsole.logLog-driver output target
logBodybooleantrue with NODE_ENV=development/test, false anywhere else (unset included)Log driver only: include the body in the log line — bodies carry reset links/tokens
previewsMailPreview[]—Mails exposed by the basalt mail:preview dev server

Failure modes & troubleshooting ​

Error / symptomCodeWhen
NotificationValidationErrorNOTIFICATION_INVALIDPayload fails the notification's Zod schema — nothing is sent
UnknownChannelErrorNOTIFICATION_UNKNOWN_CHANNELA definition targets a channel with no registered driver (e.g. sms without an SmsChannel)
MissingRendererErrorNOTIFICATION_MISSING_RENDERERA definition targets a channel but defines no via.<channel> renderer
RecipientEmailMissingErrorNOTIFICATION_EMAIL_MISSINGMail channel: recipient has no email — lands in the report's failed, other channels still deliver
RecipientPhoneMissingErrorNOTIFICATION_PHONE_MISSINGSMS/WhatsApp: recipient has no phone — same isolation
MailValidationErrorMAIL_INVALIDMail data fails its schema
MailIncompleteErrorMAIL_INCOMPLETENo recipient in the envelope, or no sender anywhere (envelope or plugin from)
MailHeaderInjectionErrorMAIL_HEADER_INJECTIONCR/LF or malformed address in subject/from/to/cc/bcc/replyTo — blocked before any driver
MailDeliveryErrorMAIL_DELIVERY_FAILEDAn API driver (Resend, SES, Mailgun) got a non-success provider response
Boot throws Unknown mail driver "…"—Typo'd driver string — fail-loud by design; valid: smtp, resend, ses, mailgun, memory, log
Mail bodies show (body redacted in production — …)—Log driver + NODE_ENV not explicitly development/test (unset counts as production); pass logBody: true or configure a real driver

Pair with @basaltkit/i18n to render outbound content in the recipient's locale, and @basaltkit/queue to deliver asynchronously.

Released under the MIT License.