Skip to content

About

A flexible package for implementing transactional notifications

Resources

Stars

9 stars

Watchers

4 watching

Forks

Repository files navigation

VintaSend TypeScript

A flexible package for implementing transactional notifications in TypeScript.

Features

  • Storing notifications in a Database: This package relies on a data store to record all the notifications that will be sent. It also keeps its state column up to date.
  • One-off notifications: Send notifications directly to email addresses or phone numbers without requiring a user account. Perfect for prospects, guests, or external contacts.
  • File Attachments: Attach files to notifications with flexible storage backend support (S3, Azure, GCS, local filesystem, etc.), automatic deduplication, and reusable file references.
  • Scheduling notifications: Storing notifications to be sent in the future. The notification's context for rendering the template is only evaluated at the moment the notification is sent due to the lib's context generation registry.
  • Notification context fetched at send time: On scheduled notifications, the package only gets the notification context (information to render the templates) at the send time, so we always get the most up-to-date information.
  • Flexible backend: Your project's database is getting slow after you created the first million notifications? You can migrate to a faster NoSQL database in the blink of an eye without affecting how you send the notifications.
  • Flexible adapters: Your project probably will need to change how it sends notifications over time. This package allows you to change the adapter without having to change how notification templates are rendered or how the notification themselves are stored.
  • Flexible template renderers: Wanna start managing your templates with a third party tool (so non-technical people can help maintain them)? Or even choose a more powerful rendering engine? You can do it independently of how you send the notifications or store them in the database.
  • Sending notifications in background jobs: This package supports using job queues to send notifications from separate processes. This may be helpful to free up the HTTP server of processing heavy notifications during the request time.

How does it work?

The VintaSend package provides a NotificationService class that allows the user to store and send notifications, scheduled or not. It relies on Dependency Injection to define how to store/retrieve, render the notification templates, and send notifications. This architecture allows us to swap each part without changing the code we actually use to send the notifications.

Scheduled Notifications

VintaSend schedules notifications by creating them on the database for sending when the sendAfter value has passed. The sending isn't done automatically but we have a service method called sendPendingNotifications to send all pending notifications found in the database.

You need to call the sendPendingNotifications service method in a cron job or a tool for running periodic jobs.

Keeping the content up-to-date in scheduled notifications

The VintaSend class stores every notification in a database. This helps us to audit and manage our notifications. At the same time, notifications usually have a context that's used to hydrate its template with data. If we stored the context directly on the notification records, we'd have to update it anytime the context changes.

Installation

npm install vintasend
# or
yarn add vintasend

Getting Started

To start using VintaSend you just need to initialize the notification service and start using it to manage your notifications.

import { VintaSendFactory } from 'vintasend';
import type { ContextGenerator } from 'vintasend';

// context generator for Welcome notification
class WelcomeContextGenerator extends ContextGenerator {
  async generate ({ userId }: { userId: number }): { firstName: string } {
    const user = await getUserById(userId);  // example
    return {
      firstName: user.firstName,
    };
  }
}

// context map for generating the context of each notification
export const contextGeneratorsMap = {
  welcome: new WelcomeContextGenerator(),
} as const;

// type config definition, so all modules use the same types
export type NotificationTypeConfig = {
  ContextMap: typeof contextGeneratorsMap;
  NotificationIdType: number;
  UserIdType: number;
};

export function getNotificationService() {
  /* 
   Function to instanciate the notificationService 
   The Backend, Template Renderer, Logger, and Adapter used here are not included
     here and should be installed and imported separately or manually defined if 
     the existing implementations don't support the specific use-case.
  */
  const backend = new MyNotificationBackendFactory<NotificationTypeConfig>().create();
  const templateRenderer = new MyNotificationAdapterFactory<NotificationTypeConfig>().create();
  const adapter = new MyNotificationAdapterFactory<NotificationTypeConfig>().create(
    templateRenderer, true
  );
  return new VintaSendFactory<NotificationTypeConfig>().create(
    [adapter],
    backend,
    new MyLogger(loggerOptions),
    contextGeneratorsMap,
  );
}

export function sendWelcomeEmail(userId: number) {
  /* sends the Welcome email to a user */
  const vintasend = getNotificationService();
  const now = new Date();

  vintasend.createNotification({
    userId: user.id,
    notificationType: 'EMAIL',
    title: 'Welcome Email',
    contextName: 'welcome',
    contextParameters: { userId },
    sendAfter: now,
    bodyTemplate: './src/email-templates/auth/welcome/welcome-body.html.template',
    subjectTemplate: './src/email-templates/auth/welcome/welcome-subject.txt.template',
    extraParams: {},
  });
} 

Multi-Backend Configuration

VintaSend supports configuring multiple backends for redundancy, data distribution, and migration use cases.

Basic Setup

import { VintaSendFactory } from 'vintasend';

const vintasend = new VintaSendFactory<NotificationTypeConfig>().create({
  adapters,
  backend: primaryBackend,
  additionalBackends: [replicaBackend],
  logger,
  contextGeneratorsMap,
});

How It Works

  • Writes: VintaSend writes to the primary backend first, then replicates to additional backends either inline (default) or through a per-backend replication queue.
  • Reads: Read methods use the primary backend by default, but support optional backend targeting by identifier.
// Read from primary backend (default)
const notification = await vintasend.getNotification(notificationId);

// Read from a specific backend
const notificationFromReplica = await vintasend.getNotification(
  notificationId,
  false,
  'replica-backend',
);

Backend Management Operations

const report = await vintasend.verifyNotificationSync(notificationId);

if (!report.synced) {
  await vintasend.replicateNotification(notificationId);
}

const backendStats = await vintasend.getBackendSyncStats();

Asynchronous Replication Queue (Per Backend)

VintaSend supports asynchronous replication to additional backends with one queued task per destination backend.

Replication mode

Use replicationMode: 'queued' to enqueue replication instead of replicating inline in the request path.

const vintasend = new VintaSendFactory<NotificationTypeConfig>().create({
  adapters,
  backend: primaryBackend,
  additionalBackends: [replicaA, replicaB],
  logger,
  contextGeneratorsMap,
  replicationQueueService,
  options: {
    raiseErrorOnFailedSend: false,
    replicationMode: 'queued',
  },
});

Replication queue contract

The replication queue service receives both the notification id and the target backend identifier:

export interface BaseNotificationReplicationQueueService<Config extends BaseNotificationTypeConfig> {
  enqueueReplication(notificationId: Config['NotificationIdType'], backendIdentifier: string): Promise<void>;
}

When queued replication is enabled, VintaSend enqueues one replication task for each additional backend.

Worker processing

Workers should process replication with a backend target to apply replication only for the queued destination:

await vintasend.processReplication(notificationId, backendIdentifier);

You can still call processReplication(notificationId) without a target to process all additional backends.

Ordering and idempotency safety

To reduce out-of-order replication issues, backends can optionally implement conditional apply:

applyReplicationSnapshotIfNewer?(snapshot): Promise<{ applied: boolean }>;
  • If destination state is newer/equal, replication is skipped (applied: false).
  • If destination is older, snapshot is applied.
  • Duplicate-create race conditions are handled with create→update fallback in worker replication flow.

Official backends vintasend-prisma and vintasend-medplum implement this conditional apply behavior.

Version tokens

Every backend write that changes a notification takes NotificationWriteOptions as its last argument (bulkPersistNotifications takes BulkNotificationWriteOptions, one token per notification). VintaSend calls the primary without a token, so it generates a new notificationVersion. It then passes that token to each additional backend's copy of the write, which stores it as given. The writes that return no notification (cancelNotification, storeAdapterAndContextUsed, storeTemplateVersion) return { notificationVersion } so the token can be passed on. Snapshot replication (replicateNotification, processReplication) copies the snapshot's notificationVersion the same way. A backend that keeps no tokens can ignore the option; its notifications then have no notificationVersion.

Failure Handling

  • Primary backend failures fail the operation.
  • Additional backend replication failures are logged and do not fail the primary operation.
  • In queued mode, enqueue failures fall back to inline replication for affected backends.
  • This keeps primary workflows available while still enabling redundancy and eventual consistency.

Filtering and Ordering Notifications

Use filterNotifications to query notifications with pagination and optional ordering.

const notifications = await vintasend.filterNotifications(
  {
    status: 'PENDING_SEND',
  },
  1,
  25,
  {
    field: 'createdAt',
    direction: 'desc',
  },
);

orderBy shape

type NotificationOrderBy = {
  field: 'sendAfter' | 'sentAt' | 'readAt' | 'createdAt' | 'updatedAt';
  direction: 'asc' | 'desc';
};

Examples:

  • { field: 'createdAt', direction: 'desc' }
  • { field: 'sendAfter', direction: 'asc' }

Checking backend support

Use getBackendSupportedFilterCapabilities() to detect support gaps per backend.

const capabilities = await vintasend.getBackendSupportedFilterCapabilities();

if (!capabilities['orderBy.readAt']) {
  // Fallback to another ordering field
}

When using multiple backends, you can check capabilities for a specific backend identifier:

const replicaCapabilities = await vintasend.getBackendSupportedFilterCapabilities('replica-backend');

vintasend-medplum currently does not support orderBy.readAt, and reports orderBy.readAt: false.

Filtering by read date

readAtRange filters on when a notification was read, alongside sendAfterRange, createdAtRange and sentAtRange. It is newer than the other range filters, so support is opt-in per backend and both of its capability keys default to false:

const capabilities = await vintasend.getBackendSupportedFilterCapabilities();

if (capabilities['fields.readAtRange']) {
  await vintasend.filterNotifications({ readAtRange: { from: lastWeek } }, 0, 25);
}

All four date ranges share the same NULL semantics: a notification whose date field is null does not match a positive range, and because { not: ... } inverts the positive result, it is returned by a negated one. An unread notification is therefore excluded by readAtRange and returned by { not: { readAtRange } }.

Filtering by template version

requestedTemplateVersion and usedTemplateVersion filter on the two integer fields a notification records when its template renderer versions templates — what it was pinned to, and what it actually rendered. Scalar or array, like the other membership fields:

// still pinned to v3
await vintasend.filterNotifications({ requestedTemplateVersion: 3 }, 0, 25);

// went out on v1 or v2
await vintasend.filterNotifications({ usedTemplateVersion: [1, 2] }, 0, 25);

Both are opt-in per backend for the same reason readAtRange is, and their capability keys default to false. See Template Version Pinning.

Filtering on whether a field is set

hasSendAfter and hasRequestedTemplateVersion match notifications with (true) or without (false) a send time or a template pin, which a range or a version list cannot say. "Pinned, but not to V" is the pin combined with a negated version:

await vintasend.filterNotifications(
  { and: [{ hasRequestedTemplateVersion: true }, { not: { requestedTemplateVersion: 4 } }] },
  0,
  25,
);

They are new vocabulary, so fields.hasSendAfter, negation.hasSendAfter, fields.hasRequestedTemplateVersion and negation.hasRequestedTemplateVersion default to false. vintasend-prisma and vintasend-medplum support all four.

Listing IDs and versions only

filterNotificationVersions(filter, page, pageSize) returns { id, version } for each match and nothing else. A backend implementing it must not read recipients, contexts, context parameters, rendered content or attachments to answer, so it is how to count or select notifications that must not be read. Results are ordered by ID. version is an opaque token for the notification as it is now; pass it as expectedVersion to act on it only if it has not changed (see Re-pinning and Re-queuing Notifications).

It is optional on a backend; getBackendSupportedActionCapabilities() reports versions.filter, and the call throws on a backend without it. vintasend-medplum implements it with _elements=id,meta,identifier, vintasend-prisma with select: { id, notificationVersion, updatedAt }.

Filtering by ID

id takes one ID or a list. AND it with another filter to recount a batch you already hold, without listing everything else that matches:

const stillMatching = await vintaSend.filterNotificationVersions(
  { and: [filter, { id: batch.map((entry) => entry.id) }] },
  0,
  batch.length,
);

An empty list matches nothing. fields.id and negation.id default to false; vintasend-prisma supports both, vintasend-medplum supports fields.id (as _id) only.

Moving many notifications at once

repinNotifications(targets, { templateVersion, filter }) and requeueNotifications(targets, { sendAfter, templateVersion, filter }) take the { id, version } pairs filterNotificationVersions returned and act on each one only if it is still at that version, still in a status the action allows, and still matches filter. The backend checks all of that in one pass, so no notification is read before it is written:

const filter = { bodyTemplate: 'welcome', status: ['PENDING_SEND', 'FAILED'] };
const templateVersion = await vintaSend.getCurrentTemplateVersion('EMAIL', 'welcome');
if (templateVersion === null) throw new Error('welcome is not versioned');
const batch = await vintaSend.filterNotificationVersions(filter, 0, 50);
const results = await vintaSend.repinNotifications(batch, { templateVersion, filter });

A target that fails a check is skipped rather than thrown for, and its result says why: WRITTEN, UNCHANGED (already on the version), CHANGED, INVALID_STATUS, NOT_MATCHED (gone, or no longer matches filter) or FAILED. requeueNotifications sends nothing: it leaves the notifications pending, as requeueNotification does with send: false. Additional backends take each written target, as for the single actions.

Backends report repin.bulk and requeue.bulk. vintasend-medplum does it with one search (_elements=id,meta,identifier,status,sent) and one batch of If-Match JSON Patch updates per bulkActionBatchSize targets (a backend option, 100 by default); vintasend-prisma with one conditional UPDATE per target.

Case sensitivity

stringLookups.caseSensitive and stringLookups.caseInsensitive are separate capabilities, not a flag and its negation, because a backend can be unable to do either one:

Backend Reports Meaning
Case-insensitive collation (MySQL *_ci) caseSensitive: false Always matches case-insensitively; cannot be asked for a case-sensitive match.
LIKE without ILIKE or case folding caseInsensitive: false Always matches case-sensitively.
Most backends both true Either lookup can be requested.

Deriving one from the other inverts the answer for exactly the backends that had a constraint worth reporting, and then declines the one lookup they do support.

Pagination indexing

page arguments are 0-indexed in this package: the first page is page 0. vintasend-prisma and vintasend-medplum both translate it as page * pageSize, and the interface documents it as 0-indexed.

That is a convention of the backend, not of VintaSend as a whole — the Python VintaSend backends are 1-indexed. Anything that exposes page numbers of its own (an HTTP API, a UI) should ask the backend rather than hardcode an offset:

const capabilities = await vintasend.getBackendSupportedFilterCapabilities();
const firstPage = capabilities['pagination.oneIndexed'] === true ? 1 : 0;

pagination.oneIndexed defaults to false, so every TypeScript backend — including any that does not implement getFilterCapabilities() — reports the 0-indexed convention it already follows. It is the one capability whose default is false rather than true; because the defaults are merged under the backend's own report, the key is always present in what you receive, so the "missing keys mean supported" rule never applies to it in practice.

The convention covers every paginated backend method — getNotifications, getPendingNotifications, getFutureNotifications, getOneOffNotifications, filterNotifications — since a backend pages the same way throughout.

Attachment Support

VintaSend supports file attachments for notifications with an extensible architecture that allows you to choose your preferred storage backend.

Key Features

  • ✅ Flexible Storage - Support for multiple backends (AWS S3, Azure Blob, Google Cloud Storage, local filesystem, etc.)
  • ✅ Reusable Files - Upload once, attach to multiple notifications
  • ✅ Automatic Deduplication - Files with identical content stored only once
  • ✅ Streaming Support - Efficient handling of large files
  • ✅ Presigned URLs - Secure, time-limited file access (backend-dependent)
  • ✅ Custom Backends - Extensible interface to implement any storage service

Quick Start

// Example using S3 AttachmentManager (see available implementations below)
import { S3AttachmentManager } from 'vintasend-aws-s3-attachments';

// Create attachment manager (configuration varies by implementation)
const attachmentManager = new S3AttachmentManager({
  bucket: 'my-app-notifications',
  region: 'us-east-1',
  keyPrefix: 'attachments/',
});

// Create VintaSend with attachment support
const vintaSend = factory.create(
  adapters,
  backend,
  templateRenderer,
  contextGeneratorsMap,
  logger,
  attachmentManager, // Pass your chosen attachment manager
);

// Send notification with inline file upload
await vintaSend.sendNotification({
  notificationTypeId: 'order-confirmation',
  userId: '123',
  context: { orderNumber: 'ORD-12345' },
  attachments: [
    {
      file: invoiceBuffer,
      filename: 'invoice.pdf',
      contentType: 'application/pdf',
    },
  ],
});

// Send notification with pre-uploaded file reference
await vintaSend.sendNotification({
  notificationTypeId: 'welcome-email',
  userId: '456',
  context: { userName: 'John' },
  attachments: [
    {
      fileId: 'file-abc-123', // Reference to existing file
      description: 'Company brochure',
    },
  ],
});

Complete Documentation

For comprehensive guides on attachment support, storage backends, security, and best practices, see ATTACHMENTS.md.

Topics covered:

  • Available storage backend implementations
  • Creating custom AttachmentManagers for any storage service
  • Security best practices and performance optimization
  • Adapter support for sending attachments
  • Usage examples and patterns

One-Off Notifications

One-off notifications allow you to send notifications directly to an email address or phone number without requiring a user account in your system. This is particularly useful for:

  • Prospects: Send welcome emails or marketing materials to potential customers
  • Guests: Invite external participants to events or meetings
  • External Contacts: Share information with partners or vendors
  • Temporary Recipients: Send one-time notifications without creating user accounts

Key Differences from Regular Notifications

Feature Regular Notification One-Off Notification
Recipient User ID (requires account) Email/phone directly
User Data Fetched from user table Provided inline (firstName, lastName)
Use Case Registered users Prospects, guests, external contacts
Storage Same table with userId Same table with emailOrPhone

Creating One-Off Notifications

// Send an immediate one-off notification
const notification = await vintaSend.createOneOffNotification({
  emailOrPhone: 'prospect@example.com',
  firstName: 'John',
  lastName: 'Doe',
  notificationType: 'EMAIL',
  title: 'Welcome!',
  bodyTemplate: './templates/welcome.html',
  subjectTemplate: 'Welcome to {{companyName}}!',
  contextName: 'welcomeContext',
  contextParameters: { companyName: 'Acme Corp' },
  sendAfter: null, // Send immediately
  extraParams: null,
});

Using with Phone Numbers (SMS)

// Send SMS to a phone number (requires SMS adapter)
const smsNotification = await vintaSend.createOneOffNotification({
  emailOrPhone: '+15551234567', // E.164 format recommended
  firstName: 'John',
  lastName: 'Doe',
  notificationType: 'SMS',
  title: 'Welcome SMS',
  bodyTemplate: './templates/welcome-sms.txt',
  subjectTemplate: null, // SMS doesn't use subjects
  contextName: 'welcomeContext',
  contextParameters: { companyName: 'Acme Corp' },
  sendAfter: null,
  extraParams: null,
});

Database Schema Considerations

One-off notifications are stored in the same table as regular notifications using a unified approach:

  • Regular notifications: Have userId set, emailOrPhone is null
  • One-off notifications: Have emailOrPhone set, userId is null

Git Commit SHA Tracking

VintaSend can persist which source-code version executed each notification send/render flow.

Field behavior

  • Persisted notifications include gitCommitSha: string | null
  • Notification input/resend payloads do not accept this field (gitCommitSha is system-managed)
  • The SHA is resolved at execution time (send/render), not creation time

Configuring a provider

Use BaseGitCommitShaProvider with VintaSendFactory.create(...).

Preferred factory style (object parameter):

import { VintaSendFactory, type BaseGitCommitShaProvider } from 'vintasend';

const gitCommitShaProvider: BaseGitCommitShaProvider = {
  getCurrentGitCommitSha: () => process.env.GIT_COMMIT_SHA ?? null,
};

const vintaSend = new VintaSendFactory<NotificationTypeConfig>().create({
  adapters: [adapter],
  backend,
  logger,
  contextGeneratorsMap,
  gitCommitShaProvider,
});

Positional create(...) parameters are still supported for backward compatibility, but object-style configuration is recommended.

Provider examples

Environment variable (CI/CD injected):

const envProvider: BaseGitCommitShaProvider = {
  getCurrentGitCommitSha: () => process.env.GIT_COMMIT_SHA ?? null,
};

Shell command (async):

import { execSync } from 'node:child_process';

const shellProvider: BaseGitCommitShaProvider = {
  getCurrentGitCommitSha: async () => {
    try {
      return execSync('git rev-parse HEAD', { encoding: 'utf-8' }).trim() || null;
    } catch {
      return null;
    }
  },
};

Static provider (for deterministic environments):

const staticProvider: BaseGitCommitShaProvider = {
  getCurrentGitCommitSha: () => '0123456789abcdef0123456789abcdef01234567',
};

Migration Guides

Migrating to v0.7.0 (Git Commit SHA Tracking)

This migration is only needed if you're using the Prisma backend.

gitCommitSha is now persisted on notifications (regular and one-off) as a nullable, system-managed field.

  1. Update your Prisma schema (Notification model):
  • Add gitCommitSha String?
  • Add @@index([gitCommitSha])
  1. Run a migration in your app:
prisma migrate dev --name add-notification-git-commit-sha
  1. Optionally configure a BaseGitCommitShaProvider in VintaSendFactory.
  2. Do not add gitCommitSha to notification create/resend input payloads (it is provider-managed).

Migrating to v0.4.0 (Attachment Support)

Version 0.4.0 introduces file attachment support with a breaking change to the VintaSendFactory.create() method signature.

Breaking Change: The attachmentManager parameter now comes before the options parameter.

  • Old signature (v0.3.x): create(adapters, backend, logger, contextGeneratorsMap, queueService?, options?)
  • New signature (v0.4.0): create(adapters, backend, logger, contextGeneratorsMap, queueService?, attachmentManager?, options?)

Migration Steps:

  1. If you're NOT passing options - No changes needed:

    // This still works in v0.4.0
    factory.create(adapters, backend, logger, contextGeneratorsMap);
    factory.create(adapters, backend, logger, contextGeneratorsMap, queueService);
  2. If you ARE passing options as the 6th argument - Add undefined for attachmentManager:

    // Before (v0.3.x) - THIS WILL BREAK
    factory.create(adapters, backend, logger, contextGeneratorsMap, queueService, { 
      raiseErrorOnFailedSend: true 
    });
    
    // After (v0.4.0) - CORRECT
    factory.create(adapters, backend, logger, contextGeneratorsMap, queueService, undefined, { 
      raiseErrorOnFailedSend: true 
    });
  3. If you want to use attachments - Pass the attachmentManager:

    import { LocalFileAttachmentManager } from 'vintasend/local-file-attachment-manager';
    
    const attachmentManager = new LocalFileAttachmentManager({ uploadDir: './uploads' });
    
    factory.create(adapters, backend, logger, contextGeneratorsMap, queueService, attachmentManager, {
      raiseErrorOnFailedSend: true
    });
  4. For Prisma users: Add attachment models to your schema (optional, only if you want attachment support):

    # Add AttachmentFile and NotificationAttachment models to schema.prisma
    # See ATTACHMENTS.md for the complete schema
    prisma migrate dev --name add-attachment-support

Note: Attachment methods in BaseNotificationBackend are now optional. Existing backend implementations continue to work without changes. See ATTACHMENTS.md for full documentation.

Migrating to v0.3.0 (One-off Notifications)

If you're adding one-off notification support to an existing installation:

  1. Update your Prisma schema to make userId optional and add one-off fields:

    # Add the new fields to your schema.prisma
    # Then run:
    prisma migrate dev --name add-one-off-notification-support
  2. No code changes required for existing functionality - all existing notifications continue to work as before.

  3. Existing notifications are preserved - they have userId set and emailOrPhone as null.

Template Version Pinning

Some template renderers version their templates. A file on disk has no version — editing it changes what every notification renders, past and future. A store-backed renderer such as vintasend-managed-templates keeps every edit as a new version, and that makes two questions answerable that were not before: which version should this notification render, and which version did it actually go out with.

Two fields on the notification hold the answers:

Field Set by Means
requestedTemplateVersion the caller, or the service at create time Render this exact version. Absent means "whatever is current at send time".
usedTemplateVersion the service, at send time The version the renderer reported it actually used. Read-only to callers.

With a renderer whose templates are not versioned — which is most of them — both stay absent and nothing about this changes.

Pinning a single notification

Pass the version and it is used, whatever the service is configured with:

await notificationService.createNotification({
  userId: user.id,
  notificationType: 'EMAIL',
  title: 'Welcome',
  bodyTemplate: 'welcome',          // a template key, not a path
  contextName: 'welcomeContext',
  contextParameters: { userId: user.id },
  sendAfter: null,
  subjectTemplate: null,
  extraParams: null,
  requestedTemplateVersion: 3,      // render v3, now and forever
});

Repointing an existing notification works the same way:

await notificationService.updateNotification(notificationId, { requestedTemplateVersion: 4 });

Pinning without naming a version

pinTemplateVersions: true resolves whatever version is current now and records it, so a later edit to the template cannot change what an already-recorded notification renders. Ask for it per call, in the options argument that every create and update takes:

await notificationService.createNotification(
  { /* ... */ bodyTemplate: 'welcome' },
  { pinTemplateVersions: true },      // pin to whatever "welcome" is right now
);

await notificationService.updateNotification(
  notificationId,
  { bodyTemplate: 'farewell' },       // re-pinned to farewell's current version
  { pinTemplateVersions: true },
);

...or set the default for every call on the service, and override it where it does not apply:

const notificationService = new VintaSendFactory<Config>().create({
  adapters,
  backend,
  logger,
  contextGeneratorsMap,
  options: {
    raiseErrorOnFailedSend: false,
    pinTemplateVersions: true,        // the default for every create and update
  },
});

// not this one
await notificationService.createNotification(input, { pinTemplateVersions: false });

The default is off, because turning it on changes what an existing deployment sends: unpinned, a notification scheduled for next week renders whatever the template says next week, which is sometimes exactly what a team wants. The flag is never stored — it decides what requestedTemplateVersion is set to at that moment, and nothing afterwards consults it.

Key semantics:

  • The call wins over the service. pinTemplateVersions on a create or update overrides the constructor's setting in both directions; leave it out to defer to the service.
  • An explicit version always wins over both. pinTemplateVersions only decides what happens when the caller does not name a version, on create and on update alike.
  • Resolved through the renderer. The service asks the renderer for the notification type it is creating, via BaseNotificationTemplateRenderer.getLatestTemplateVersion(). The default implementation returns null — so with a file-based renderer this flag has nothing to pin and quietly does nothing.
  • Best-effort. A renderer that throws while resolving is logged and the notification is created unpinned, rather than failing the write. An unpinned notification still sends.
  • Updates re-pin only when the template changes. An update carrying a new bodyTemplate is re-pinned to that template's current version; an update to the title leaves an existing pin exactly as it was. Silently moving a pin forward is the one thing pinning exists to prevent.

Recording what actually rendered

At send time the renderer reports the version it used on the payload it returns, the adapter hands that back from send(), and the service stores it:

const notification = await notificationService.getNotification(notificationId);
notification.requestedTemplateVersion;   // 3  — what it asked for (or absent)
notification.usedTemplateVersion;        // 3  — what rendered

On an unpinned notification usedTemplateVersion is the only record of which version went out, since the template has moved on by the time anyone asks.

  • System-managed. Passing usedTemplateVersion to updateNotification throws. Set requestedTemplateVersion instead.
  • Never blocks a send. It is written after delivery, so a failure to record it is logged and the notification stays sent.
  • A pin covers the template named, not what that template builds on. With a renderer that composes templates from other templates, pinning a notification to v3 of welcome renders v3 of welcome — but a base it extends without naming a version still resolves to whatever that base is today. Pin the reference too (with version=2 on the managed_extends tag) when a template must keep composing against an exact parent. See Managed Templates.

Filtering

Both fields are filterable, by a single version or a list:

// still pinned to v3
await notificationService.filterNotifications({ requestedTemplateVersion: 3 }, 0, 20);

// went out on v1 or v2 — the query after finding a bug in an old version
await notificationService.filterNotifications({ usedTemplateVersion: [1, 2] }, 0, 20);

Both capability keys default to false, for the same reason fields.readAtRange does: they are vocabulary no backend implemented when they were introduced, so a true default would have every shipped and third-party backend claim a filter it would silently ignore. vintasend-prisma and vintasend-medplum both declare them supported. Check before you rely on them:

const capabilities = await notificationService.getBackendSupportedFilterCapabilities();
capabilities['fields.usedTemplateVersion'];

What an implementation package has to do

Everything below is optional. A renderer, adapter, or backend that ignores all of it keeps working exactly as it did.

  • A renderer whose templates are versioned overrides getLatestTemplateVersion(templateKey), honours the notification's requestedTemplateVersion in render(), and sets templateVersion on the payload it returns.
  • An adapter returns the render from send() instead of discarding it. Returning nothing is still valid — the service then records nothing.
  • A backend stores requestedTemplateVersion (an ordinary field on the notification it is handed) and implements storeTemplateVersion(). That method is optional on the interface, so a backend with nowhere to put it needs no changes at all; the cost is only that usedTemplateVersion stays absent on the records it holds.

Re-pinning and Re-queuing Notifications

Two service methods change an existing notification, so the database never has to be edited by hand. Both work on regular and one-off notifications, write to every configured backend, and refuse with a NotificationActionError before writing anything. Its reason is one of:

reason Meaning
NOT_FOUND No notification has that ID in the primary backend.
INVALID_STATUS The status does not allow the action; status says which.
NO_TEMPLATE_VERSION A re-pin with no version found none: the renderer does not version templates.
CHANGED The notification is no longer at expectedVersion, or changed between the backend's read and its write.
UNSUPPORTED The primary backend cannot honour an option given (expectedVersion, or templateVersion on a re-queue).

repinNotification

This moves a notification that has not been delivered onto a template version: the current one by default, or the one you name.

await notificationService.repinNotification(notificationId);                         // current version
await notificationService.repinNotification(notificationId, { templateVersion: 4 }); // exactly v4
  • Allowed in PENDING_SEND, FAILED and CANCELLED. A sent notification's pin records what it was asked to render when it went out, so SENT and READ are refused.
  • Changes requestedTemplateVersion only. It neither sends nor changes the status, and works whether the notification was pinned before or not. Re-pinning to the pinned version writes nothing.
  • "The current version" is getCurrentTemplateVersion(notificationType, templateKey), which is public: show it as "the version new notifications get" and it cannot disagree with what a re-pin or pinTemplateVersions pins. With vintasend-managed-templates it is the key's newest active version, or null when nothing is published or that version is a base.
  • NO_TEMPLATE_VERSION means no version was named and the renderer for that notification type reports none. A file-based renderer always answers this way.
  • Unlike updateNotification, it moves the pin without changing bodyTemplate.

requeueNotification

This puts a FAILED or CANCELLED notification back into PENDING_SEND under the same ID. It retries that notification. resendNotification creates a new one from a notification that was delivered.

await notificationService.requeueNotification(notificationId);                     // keep its sendAfter
await notificationService.requeueNotification(notificationId, { sendAfter: null }); // send now
await notificationService.requeueNotification(notificationId, { sendAfter: tomorrow });
await notificationService.requeueNotification(notificationId, { templateVersion: 4 }); // re-pin too, in one write
await notificationService.requeueNotification(notificationId, { send: false });     // leave it to the pending sender
  • Sends when due. Once pending again, a notification whose sendAfter is null or past is sent at once, as createNotification does. An adapter with enqueueNotifications puts it back on the queue service. A future sendAfter leaves it for sendPendingNotifications.
  • Returns the outcome. The notification comes back as it stands after any send the call started, read again from the primary backend: SENT when it went out, FAILED when the adapter failed, PENDING_SEND when it is waiting (scheduled, queued, send: false, or the send stopped before an adapter). This holds with raiseErrorOnFailedSend: false, so there is no need to read it again yourself.
  • send: false re-queues without sending, even a due notification: it waits for whatever runs sendPendingNotifications. No adapter is used, so a process that only re-queues can be built with adapters: [] and needs no delivery credentials.
  • templateVersion pins the notification and re-queues it in one backend write, so it is never left half-moved. It needs a backend reporting requeue.templateVersion; elsewhere it is refused with UNSUPPORTED. The send time is kept unless sendAfter is given, and a due notification is sent as above. repinNotification followed by requeueNotification still works, in two writes.
  • Keeps everything else. Stored contextUsed and attachments are unchanged; sentAt, which markAsFailed sets to the failure time, is cleared.
  • PENDING_SEND, SENT and READ are refused. A pending notification is already queued, and re-queuing a delivered one would deliver it twice under one record.

vintasend-api exposes both as POST /api/v1/notifications/{id}/repin and /requeue; vintasend-dashboard-core wraps them as useRepinNotification and useRequeueNotification.

Acting only on a notification that has not changed

Both methods take expectedVersion, the token filterNotificationVersions returned for the notification. The backend then writes only if the notification is still at that version, and otherwise refuses with CHANGED, writing nothing. So a notification counted and confirmed by an admin is not moved if a worker sent it, or someone edited it, in between:

const [entry] = await notificationService.filterNotificationVersions(
  { bodyTemplate: 'welcome', status: 'FAILED' },
  0,
  100,
);
await notificationService.requeueNotification(entry.id, {
  templateVersion: 4,
  expectedVersion: entry.version,
});

With additional backends, the token is the same on every backend: the primary generates it on each write, and replication stores that token on the additional backends instead of letting each one generate its own. So versions can be listed from an additional backend and acted on, as always, at the primary:

const entries = await notificationService.filterNotificationVersions(filter, 0, 100, 'reporting');
await notificationService.requeueNotification(entries[0].id, {
  expectedVersion: entries[0].version,
});

If the additional backend has not caught up with the primary's latest write, the token it listed is older, and the action is refused with CHANGED; it is never applied over a newer write.

A backend that cannot check versions reports so, and the option is refused with UNSUPPORTED before anything is read or written. It is never ignored. Check first with:

const capabilities = await notificationService.getBackendSupportedActionCapabilities();
// { 'repin.expectedVersion', 'requeue.expectedVersion', 'requeue.templateVersion', 'versions.filter' }

Every key defaults to false. vintasend-prisma and vintasend-medplum report all four.

What a backend has to do

requeueNotification(notificationId, { sendAfter? }) is required on BaseNotificationBackend from 1.0.0-alpha10. It must:

  • move only a notification in REQUEUEABLE_NOTIFICATION_STATUSES (FAILED, CANCELLED) and throw for any other, checking and writing in one step where the store allows it;
  • set status to PENDING_SEND and clear sentAt;
  • set sendAfter when the key is present (null included) and leave it alone when it is absent;
  • return the notification as getNotification would, attachments included, because the service sends what it returns.

Everything else is optional, and announced through getActionCapabilities():

Capability What the backend does
requeue.templateVersion requeueNotification sets requestedTemplateVersion from options.templateVersion in the same write.
requeue.expectedVersion requeueNotification throws NotificationActionError CHANGED, writing nothing, unless the notification is at options.expectedVersion.
repin.expectedVersion Implements repinNotification(id, templateVersion, { expectedVersion? }): refuses a delivered notification (INVALID_STATUS) and a changed one (CHANGED), writes nothing when the pin already matches, and changes only the pin.
versions.filter Implements filterNotificationVersions(filter, page, pageSize), returning { id, version } ordered by ID without reading content.

The service passes templateVersion and expectedVersion only to a backend that reports them. Without repinNotification, a re-pin goes through persistNotificationUpdate as before. Additional backends receive the writes unconditionally: a version token belongs to the primary backend.

vintasend-prisma does every move in one conditional UPDATE, with the status, and expectedVersion as updatedAt, in its WHERE. vintasend-medplum writes with If-Match on the version it read, for both re-pin and re-queue. Medplum's cancelNotification deletes the Communication, so only failed notifications can be re-queued there.

Glossary

  • Notification Backend: It is a class that implements the methods necessary for VintaSend services to create, update, and retrieve Notifications from the database.
  • Notification Adapter: It is a class that implements the methods necessary for VintaSend services to send Notifications through email, SMS or even push/in-app notifications.
  • Template Renderer: It is a class that implements the methods necessary for VintaSend adapter to render the notification body.
  • Requested template version: Which version of its template a notification should render, when its renderer versions templates. Set by the caller or resolved at create time; absent means "whatever is current at send time". See Template Version Pinning.
  • Used template version: Which version actually rendered a notification, recorded by the service at send time from what the renderer reported. System-managed — a caller sets requestedTemplateVersion instead.
  • Notification Context: It's the data passed to the templates to render the notification correctly. It's generated when the notification is sent, not on creation time
  • Context generator: It's a class defined by the user context generator map with a context name. That class has a generate method that, when called, generates the data necessary to render its respective notification.
  • Context name: The registered name of a context generator. It's stored in the notification so the context generator is called at the moment the notification will be sent.
  • Context generators map: It's an object defined by the user that maps context names to their respective context generators.
  • Queue service: Service for enqueueing notifications so they are sent by an external service.
  • Logger: A class that allows the NotificationService to create logs following a format defined by its users.
  • One-off Notification: A notification sent directly to an email address or phone number without requiring a user account. Used for prospects, guests, or external contacts.
  • Regular Notification: A notification associated with a user account (via userId). Used for registered users in your system.
  • AttachmentManager: A class that handles file storage operations (upload, download, delete) for notification attachments. Supports S3, Azure, GCS, and custom storage backends.
  • Attachment: A file attached to a notification, either uploaded inline or referenced from previously uploaded files. Supports automatic deduplication and reuse across multiple notifications.
  • Managed Template: A notification template stored in a database rather than in a file, so it can be edited without a deploy. Versioned, never edited in place, and published deliberately through a draft → active → inactive → archived lifecycle. See Managed Templates.
  • Template Manager Backend: A class that implements the methods necessary for storing, versioning, tagging and querying managed templates. The template equivalent of a Notification Backend.

Managed Templates

A template renderer reads templates from wherever its engine looks, which is usually files on disk — so every copy change is a deploy. vintasend-managed-templates (src/implementations/vintasend-managed-templates) moves templates into a data store instead: someone who is not a developer edits them, every edit is a new version, and a version is published deliberately rather than the moment it is saved.

It is storage-agnostic — it defines the seam, not the database — and it adds four things on top:

  • Versioning. A write creates the next version and leaves the previous one exactly as it was, so a notification that already went out against v1 renders v1 forever.
  • A lifecycle with an audit trail. draft → active → inactive → archived, with every move recorded and allowedTransitions on every payload so a UI never has to discover the rules by catching errors.
  • Composition. Stored templates reach the engine as source, so extends/include have nothing to load. The package resolves its own {% managed_extends %} / {% managed_block %} / {% managed_include %} tags against the store before the engine runs, and hands it one flat string.
  • Tags and filtering, spelled the same way VintaSend spells its notification filters.

To send through it, wrap a renderer and set the notification's bodyTemplate to a template key instead of a path. Nothing else about creating or sending notifications changes.

Wrap one whose engine cannot run code. A managed template is source that anyone who can edit templates hands straight to the engine: Liquid evaluates expressions and filters only, while Pug compiles a template to JavaScript and runs it, so with Pug editing a template is running code on the server. Keep Pug for templates that live in your repository.

import { LiquidEmailTemplateRendererFactory } from 'vintasend-liquidjs';
import { ManagedTemplateEmailRenderer, ManagedTemplateService } from 'vintasend-managed-templates';
import { MedplumTemplateManagerBackend } from 'vintasend-medplum-template-manager';

const managerBackend = new MedplumTemplateManagerBackend(medplum);
const liquidRenderer = new LiquidEmailTemplateRendererFactory<Config>().create({
  renderLimit: 1_000, // milliseconds: an edited template cannot make a send hang
  strictFilters: true,
});
const renderer = new ManagedTemplateEmailRenderer<Config>(managerBackend, liquidRenderer);
const templates = new ManagedTemplateService<Config>(managerBackend, renderer);

await notificationService.createNotification({
  // ...
  bodyTemplate: 'welcome', // a managed template key, not a file path
});

The package's README documents the tag language, the lifecycle, the filter vocabulary and what a template manager backend has to implement. There is a Python sibling, vintasend-managed-templates, and the two agree on the tag language, the slug rules and the filter vocabulary — so a store written by one is readable by the other.

Implementations

Community

VintaSend has many backend, adapter, and template renderer implementations. If you can't find something that fulfills your needs, the package has very clear interfaces you can implement and achieve the exact behavior you expect without loosing VintaSend's friendly API.

Officially supported packages

Backends
  • vintasend-prisma: Uses Prisma Client to manage the notifications in the database.
  • vintasend-medplum: Uses Medplum FHIR resources (Communication, Binary, Media) to manage notifications in healthcare applications.
Adapters
Attachment Managers
  • vintasend-aws-s3-attachments: AWS S3 storage backend with presigned URLs and streaming support. Also works with S3-compatible services (MinIO, DigitalOcean Spaces, Cloudflare R2, etc.).
  • vintasend-medplum: FHIR-compliant file storage using Binary and Media resources for healthcare applications.
Template Managers

Storage for managed templates — where the versions, tags and status history live.

Template Renderers
  • vintasend-liquidjs: Renders emails and SMS using LiquidJS, from template files or an in-memory template map.
  • vintasend-pug: Renders emails using Pug. Pug runs the JavaScript in a template, so use it only for templates in your repository, never for managed templates someone can edit.
  • vintasend-react-email: Renders emails using React Email, including uncompiled TS/TSX template support.
Loggers

Tools

A dashboard for inspecting, previewing, resending and cancelling notifications, split into an API and a UI so the UI can be reused with any implementation of the API's contract — including one built on the Python vintasend package.

  • vintasend-api (src/tools/vintasend-api): REST API that exposes a configured VintaSend service over HTTP. Its openapi.yaml is the normative contract. Mount it in your own server with createApp, or run it on its own with the vintasend-api command.
  • vintasend-dashboard (src/tools/vintasend-dashboard): Next.js UI that consumes that contract. It holds no backend credentials of its own.

And an API for editing the templates themselves, sharing its openapi.yaml byte-for-byte with the Python implementation so one generated client works against either server.

  • vintasend-templates-management-api (src/tools/vintasend-templates-management-api): REST API over a configured ManagedTemplateService — versions, the status lifecycle, tags, composition and previews. Mount it in your own server with createApp, or run it on its own with the vintasend-templates-management-api command.

Examples

Examples of how to use VintaSend in different context are available on the vintasend-ts-examples repository.

Development

  1. Clone the repository
  2. Install dependencies:
npm install
# or
yarn
  1. Run tests:
npm test
# or
yarn test

Contributing

Feel free to open issues and submit pull requests.

Release Process

This project uses a two-step automated release process:

  1. Bump versions: npm run release:bump
  2. Update CHANGELOG.md: Edit manually
  3. Publish: npm run release:publish

Optional publish skips:

  • npm run release:publish -- --skip=vintasend-medplum,vintasend-ts-twilio
  • npm run release:publish -- --skip-root
  • npm run release:publish -- --skip=root,vintasend-medplum

For detailed instructions, see:

Creating new implementations

There's a template project for creating new implementations that already includes basic dependencies, configuration for tests, and Github Actions hooks. You can find it in vintasend-ts/src/implementations/vintasend-implementation-template

License

This project is licensed under the MIT License - see the LICENSE file for details.

Commercial Support

alt text

This project is maintained by Vinta Software and is used in products of Vinta's clients. We are always looking for exciting work! If you need any commercial support, feel free to get in touch: contact@vinta.com.br

About

A flexible package for implementing transactional notifications

Resources

Stars

9 stars

Watchers

4 watching

Forks

Releases

Packages

Used by

Contributors

Languages