[data-reveal]{opacity:1!important;transform:none!important}
AntelopeJS DMS
DocumentationSending notifications

Sending notifications

Build a notification, then send it to users, roles or everyone, with delivery rules and send options.

Sending takes two steps. Notification() starts a builder that you fill field by field. .build() closes it and returns a SendableNotification, which carries the dispatch methods.

The Read notifications walkthrough shows the open bell with one unread message. It describes in prose how a message reaches every open session of its recipient without a reload, and no other account. The Notification preferences walkthrough explains that turning a subject off stops new notifications of that subject while the messages already in the inbox stay.

typescript
import {
  GeneralSubject,
  Notification,
} from "@antelopejs/interface-dms/notifications";

await Notification()
  .icon("i-ph-bell")
  .title("Deployment finished")
  .description("The staging deployment completed successfully.")
  .subject(GeneralSubject)
  .build()
  .toUser(userId);

A SendableNotification is immutable and holds no recipient, so you can build once and dispatch several times.

MethodSignatureDescription
toUser(userId: string, options?: SendOptions) => Promise<void>Send to one user.
toUsers(userIds: string[], options?: SendOptions) => Promise<void>Send to a list of users.
toUsersIdempotently(userIds: string[], idempotencyKey: string, options?: SendOptions) => Promise<void>Send a durable event once per recipient, including after dismissal.
toRoles(roleIds: string[], options?: RoleSendOptions) => Promise<void>Send to every user holding at least one of the roles, in options.tenantId when set.
broadcast(options?: SendOptions) => Promise<void>Send to every user.

Building a notification

Notification() takes no arguments and returns a fresh NotificationBuilder. Every setter stores its value and returns the builder, so calls chain in any order.

typescript
import { Notification } from "@antelopejs/interface-dms/notifications";
import { orderSubject } from "./notifications";

const shipped = Notification()
  .icon("i-ph-truck")
  .title("$shop.notifications.order_shipped.title")
  .description("$shop.notifications.order_shipped.description")
  .params({ orderRef: "A-1043" })
  .subject(orderSubject)
  .linkTo("/shop/orders")
  .build();
MethodTypeDescription
.icon(value)stringIcon shown next to the notification, in the dashboard icon syntax, for example i-ph-truck. Required.
.title(value)stringTitle line. Required.
.description(value)stringBody line. Required.
.subject(subject)NotificationSubjectInfoThe subject the notification is filed under. It decides the category and the user preference that gates delivery. Required.
.linkTo(value)stringDestination the notification links to, such as /settings/user/profile. Optional.
.params(value)Record<string, string | number>Interpolation values stored with the notification. Optional.
.tone(value)NotificationTone ("neutral", "primary", "success", "warning", "error")Colour of the icon well that the inbox lists the notification with. Optional. Without it, the well is primary while unread and neutral once read.

The subject comes from Categories and subjects. It is either one you declared with NotificationSubject() or one of the built-in constants.

A title or a description is either literal text or a $-prefixed translation key, following the DMS translation convention. With a key, the values passed to .params() are the interpolation values for that key. The DMS writes its own account notifications that way:

typescript
import {
  Notification,
  SecuritySubject,
} from "@antelopejs/interface-dms/notifications";

await Notification()
  .icon("i-ph-sign-in")
  .title("$dms.notifications.messages.new_login.title")
  .description("$dms.notifications.messages.new_login.description")
  .params({ device: "Firefox on Linux", country: "France" })
  .subject(SecuritySubject)
  .linkTo("/settings/user/security")
  .build()
  .toUser(userId);

Required fields are checked by the type system

NotificationBuilder<Set> tracks in its type parameter which fields you have supplied. .icon() returns NotificationBuilder<Set | "icon">, .title() adds "title", and the other setters add their own names. build() declares a this parameter that only accepts a builder whose Set covers RequiredFields:

typescript
type RequiredFields = "icon" | "title" | "description" | "subject";

A chain that skips one of the four does not compile, because this is typed never at the build() call:

typescript
const broken = Notification().icon("i-ph-bell").title("Hello").build();

That chain fails because it never supplies the description and the subject. The type check happens at the call site. build() also checks at runtime, for builders whose type parameter was written by hand or whose chain went through any. It throws Notification is missing required fields: description, subject, naming the fields still missing. A field set to undefined counts as missing. .linkTo(), .params() and .tone() never affect the check.

build() returns a SendableNotification that holds a frozen copy of the data, so reusing the builder afterwards cannot change a notification you already built.

Sending to a single user

toUser(userId, options?) sends one copy to one user. It accepts an idempotency key. readScope has no effect for this method.

typescript
import { Controller, Post } from "@antelopejs/interface-api";
import { AuthRawUser } from "@antelopejs/interface-dms/auth";
import type { User } from "@antelopejs/interface-dms/auth/db";
import {
  GeneralSubject,
  Notification,
} from "@antelopejs/interface-dms/notifications";

export class NotificationDemoController extends Controller("/api/notification") {
  @Post("send")
  async send(@AuthRawUser() user: User) {
    await Notification()
      .icon("i-ph-bell")
      .title("Notification sent")
      .description("This notification was sent from a route handler.")
      .subject(GeneralSubject)
      .build()
      .toUser(user._id);

    return { success: true };
  }
}

Sending to several users

toUsers(userIds, options?) sends to a list of user ids. A duplicate id in the list still produces one notification for that user. The examples in this section and the two after it dispatch the shipped notification built earlier on this page.

typescript
await shipped.toUsers([ownerId, managerId], { readScope: "shared" });

Sending to roles

toRoles(roleIds, options?) finds the users that hold any of the given roles and sends to them. An empty roleIds array sends nothing, and so does a set of roles that nobody holds.

typescript
await shipped.toRoles([adminRoleId], { readScope: "shared", tenantId });

Role ids are the DMS role identifiers that the DMS tenancy and permissions guide describes, and each one belongs to a tenant. tenantId (RoleSendOptions) limits the recipients to that tenant's members. Without it, the DMS looks up the role holders in every tenant, so a user holding the role in any tenant is included.

Broadcasting

broadcast(options?) sends to every user.

typescript
await shipped.broadcast();

Send options

Every dispatch method accepts an optional SendOptions object.

OptionTypeDescription
readScopeReadScope (optional)Read-state grouping for a multi-recipient send. Defaults to "individual". See Read scope.
idempotencyKeystring (optional)Stable event key, unique across producers. Prefix it with your module ID. Reusing it for a recipient preserves the original notification and its dismissal state.
dedupeboolean (optional)With false, the DMS stores every unkeyed send, even one identical to a notification the recipient got less than 10 seconds earlier. Defaults to true. See Repeated sends.
tenantIdstring (optional)The workspace the notification is about. The e-mail channel receives it as data.tenantId. With toRoles, it also limits the recipients to the members of this tenant holding the roles; every tenant when unset.

Pick "shared" for an alert that only needs one person to act on it, and "individual" for anything each recipient has to see.

typescript
import type { SendOptions } from "@antelopejs/interface-dms/notifications/types";

const forEveryone: SendOptions = { readScope: "individual" };
const handleOnce: SendOptions = { readScope: "shared" };

Repeated sends

The DMS drops an unkeyed notification identical to one the same user received less than 10 seconds earlier. Identical means the same recipient, title, description, params, link, category, subject, tone and icon. A form submitted twice, or a hook firing on every instance, leaves one row. Two notices worded alike but filed under different subjects, or drawn with a different tone or icon, are two notices.

A sender whose repeats must all arrive, such as a counter or a chat, passes { dedupe: false } to any send method.

The check holds across instances. The row ID derives from the recipient, the content and a 10-second window, so the database refuses the second insert. A copy stored in the previous window also counts. The same notification sent again later arrives as usual, and so does one whose params differ, such as a count or a timestamp. The DMS deduplicates keyed sends by their key instead, as the next section describes.

Retrying durable events

Use the same event key on every outbox retry. The first delivery stored under a key wins. A later send under the same key returns without storing anything, even when its content differs, such as a count recomputed on retry. A producer that keys a notification per period therefore needs no guard against a duplicate-key error. toUsersIdempotently is equivalent to passing idempotencyKey to toUsers. Its key argument takes precedence over a key in options.

Every module of the deployment shares the key space. The DMS stores one row per key and recipient, whatever module or category sent it. A reused key counts as already delivered, so when two modules build the same key for the same user, the second notification is lost without any error. Namespace your keys with your module ID, as in mailing:digest:2026-10-13T09 rather than digest:2026-10-13T09.

typescript
await shipped.toUsers([ownerId, managerId], { idempotencyKey: event.id });
await shipped.toUsersIdempotently([ownerId, managerId], event.id);

The DMS derives a SHA-256 row ID from the event key and the recipient ID, and performs a plain insert. If the insert fails, it reads the row under that ID. When that row is a keyed delivery to the same recipient, the send returns without an error. Otherwise the DMS rethrows the insert error, so an outbox can retry. A repeated attempt never replaces the row or resets its timestamps or read state.

Single and bulk dismissal keep keyed rows as hidden delivery receipts. Lists, previews, counts, single lookups and read operations exclude these rows, and retries do not recreate them. The DMS still deletes a dismissed unkeyed notification, and delivers an unkeyed send again outside the 10-second repeat window. Receipts keep the notification content with no expiry. Do not delete or expire these rows while their event keys can still be retried, and account for this retention in your data-erasure policies.

A shared-read send derives a stable group ID from the event key. The DMS checks recipient membership and preferences again on each attempt, so a retry can add recipients that were missing before without duplicating the deliveries that succeeded. A recipient added after another recipient has marked the group read starts unread. Retries keep the state of the existing recipients and do not replay past read actions.

Realtime publishing is best-effort and happens only after a newly inserted delivery. A crash or a lost acknowledgement can leave a stored notification without a realtime event, and a retry does not replay it. The delivery rules still apply, and a skipped recipient gets no receipt.

Delivery rules

Every dispatch method resolves to one delivery per user, so the DMS applies the same rules to each of them:

  • The subject must be registered. The DMS drops a notification whose subject was never registered through NotificationSubject(). See Declaration order.
  • The title must not be empty. The DMS drops a notification whose title is empty or only whitespace, and logs [DMS] Notification without a title not delivered.
  • The user preference decides. The DMS skips a delivery when the recipient has turned off the categoryId:subjectId pair in their notification settings. Preferences default to enabled, so a subject a user has never touched is delivered. A locked subject is delivered whatever the stored preference.
  • Skipping is silent. A skipped delivery is not an error. The promise resolves normally, and there is no per-recipient result to inspect.
  • Each recipient gets a row. Each recipient gets their own stored notification. With readScope: "shared", the DMS ties those copies together for read state, and they stay separate rows.
  • Stored notifications are pushed live. The DMS also publishes each new delivery on the recipient's realtime stream, so the dashboard's badge and preview update without a reload.
  • Stored notifications reach the e-mail channel. When a module registers the e-mail channel and the subject offers e-mail, each new delivery is also handed to the channel for recipients who have e-mail on. A repeat or a retry that stores nothing new is not mailed. See E-mail.

A send can be skipped for reasons outside your control, so treat notifications as best-effort and do not make a workflow depend on one having been stored. To keep a failed send from breaking the operation that triggered it, wrap the call:

typescript
import { Logging } from "@antelopejs/interface-core/logging";
import {
  AccountSubject,
  Notification,
} from "@antelopejs/interface-dms/notifications";

export async function notifyWelcome(userId: string, name: string) {
  try {
    await Notification()
      .icon("i-ph-hand-waving")
      .title("$dms.notifications.messages.welcome.title")
      .description("$dms.notifications.messages.welcome.description")
      .params({ name })
      .subject(AccountSubject)
      .linkTo("/settings/user/profile")
      .build()
      .toUser(userId);
  } catch (error) {
    Logging.Error(`Failed to notify "${userId}": ${String(error)}`);
  }
}

Importing the types

The interface root exports Notification() and the data types. The types subpath exports the data types alone. The two classes come from the modules that define them, which you need only to name them explicitly:

SymbolImport from
Notification@antelopejs/interface-dms/notifications
NotificationData, SendOptions, RoleSendOptions, RequiredFields@antelopejs/interface-dms/notifications or @antelopejs/interface-dms/notifications/types
NotificationBuilder@antelopejs/interface-dms/notifications/builder
SendableNotification@antelopejs/interface-dms/notifications/sendable

NotificationData is the shape the builder assembles. It holds icon, title, description and subject, plus the optional linkTo, params and tone, and the tenantId a send names. Name it when you carry notification content around before you build it:

typescript
import { Notification } from "@antelopejs/interface-dms/notifications";
import type { NotificationData } from "@antelopejs/interface-dms/notifications/types";
import type { SendableNotification } from "@antelopejs/interface-dms/notifications/sendable";

function fromData(data: NotificationData): SendableNotification {
  const builder = Notification()
    .icon(data.icon)
    .title(data.title)
    .description(data.description)
    .subject(data.subject);

  if (data.linkTo) {
    builder.linkTo(data.linkTo);
  }
  if (data.params) {
    builder.params(data.params);
  }
  if (data.tone) {
    builder.tone(data.tone);
  }

  return builder.build();
}