Star
API reference

Server

The Node side of notifkit: the server you run, the events it emits, and the interfaces you implement.

NotifkitServer

import { NotifkitServer } from "notifkit";

const server = new NotifkitServer({
  services: ["all"],
  redisUrl: process.env.REDIS_URL,
  databaseUrl: process.env.DATABASE_URL,
  providers: [new ResendTransport({ … })],
});
await server.start();
OptionDefaultNotes
servicesrequiredAny of api, enricher, engine, delivery, scheduler, ai, workflow, events, or all.
redisUrl, databaseUrlenvRequired in production. In development, leaving both out starts throwaway containers.
port3000
logLevelinfofatal through trace, or silent.
nodeEnvdevelopmentdevelopment, test or production.
providers[]Transports, registered at priority 0.
autoMigratetrueRun migrations on start.
aiModelnoneA Vercel AI SDK model, for aiPrompts.
workerConcurrency10Messages in parallel per worker.
deliveryConcurrencyworkerConcurrencyIn-flight sends per delivery worker.
fusedPipelinefalsePass single-user sends between enricher, engine and delivery in memory.
adminUsernone{ email, password, username? }: first dashboard login.
redisOptions.maxQueueLength100000Backlog warning threshold (QUEUE_MAX_LEN).
dbOptions{ maxConnections?, schema? }.

start() resolves once every selected service is up. stop() drains in-flight work and closes connections.

Environment variables

Constructor options win over environment variables, which win over .env. What each does is in Operations.

VariableDefault
NODE_ENVdevelopment
LOG_LEVELinfo
PORT3000
HOST127.0.0.1
REDIS_URLredis://localhost:6379
DATABASE_URLpostgres://platform:platform@localhost:5432/notifkit
DB_SCHEMApublic
DB_MAX_CONNECTIONS2
ADMIN_API_KEYunset
ADMIN_EMAIL, ADMIN_PASSWORD, ADMIN_USERNAMEunset
PUBLIC_URLunset
UNSUBSCRIBE_SECRETunset (required in production for api)
CORS_ORIGINunset
TRUST_PROXYfalse
WORKER_CONCURRENCY10
DELIVERY_CONCURRENCYWORKER_CONCURRENCY
PIPELINE_FUSEDfalse
QUEUE_MAX_LEN100000
IDEMPOTENCY_TTL_SECONDS3600
RATE_LIMIT_PER_HOUR100
SEGMENT_MAX_USERS100000
LOG_FLUSH_INTERVAL_MS500
LOG_BUFFER_MAX_SIZE5000
LOG_RETENTION_DAYSunset (keep forever)

Events

NotifkitServer is an EventEmitter. Events fire in the process where the work happens.

EventArguments
delivery:delivered(taskId, providerMessageId, channel, projectId)
delivery:failed(taskId, error, channel, projectId)
notification:skipped({ projectId, eventId, recipientId, reason })
notification:throttled(recipientId, count)
notification:failed(eventId, error, eventType): a message failed for good, usually into the dead-letter queue.
notification:canceled({ projectId, taskId })

A skip's reason is user_opted_out, channel_disabled, template_not_found, no_active_contacts or suppressed. A send dropped when its scheduled time arrives can also give recipient_not_found or contact_inactive.

Transport interface

import { registerTransport, type Transport } from "notifkit";

interface Transport {
  readonly channel: NotificationChannel;
  readonly limits?: { limit: number; windowSeconds: number };  // shared across processes
  send(task: NotificationDispatchedPayload): Promise<DeliveryResult>;

  // Webhooks: route mounted on the api service when webhookPath and parseWebhook are set.
  webhookPath?: string;
  verifyWebhookChallenge?(query: URLSearchParams): Promise<string | undefined> | string | undefined;
  verifyWebhook?(rawBody: string, headers: IncomingHttpHeaders): Promise<boolean> | boolean;
  parseWebhook?(body: any, rawBody?: string, headers?: IncomingHttpHeaders): Promise<WebhookEvent[]>;
}

interface DeliveryResult {
  success: boolean;
  providerMessageId?: string;
  error?: string;
  retryable?: boolean;     // false: a bad address or rejected sender, not retried
  invalidToken?: boolean;  // push: deactivates the contact
}

interface WebhookEvent {
  providerMessageId: string;
  status: "opened" | "clicked" | "bounced" | "complained" | "unsubscribed";
  recipient?: string;      // required for the event to suppress the address
  bounceType?: "hard" | "soft";  // only "hard" suppresses
  timestamp?: Date;
  metadata?: Record<string, unknown>;
}

registerTransport(transport, 10);  // higher priority is tried first

send() receives the task below. renderedContent.content is the template with placeholders filled, destination is the address, deliveryOptions.headers carries unsubscribe headers for email, and signal aborts after 10 seconds. Return failures instead of throwing.

{
  "projectId": "b2a4c1d0-5e6f-4a7b-8c9d-0e1f2a3b4c5d",
  "taskId": "7e0d3f2a-1b4c-4d5e-8f60-7a8b9c0d1e2f:41a9e6b2-3c4d-4e5f-9a6b-7c8d9e0f1a2b",
  "enrichedEventId": "3a9b8c7d-6e5f-4a3b-9c2d-1e0f9a8b7c6d",
  "recipientId": "usr_123",
  "channel": "email",
  "priority": "normal",
  "templateId": "order-confirmed",
  "templateVariables": {
    "orderId": "99214"
  },
  "recipient": {
    "id": "usr_123",
    "email": "[email protected]",
    "locale": "en",
    "timezone": "America/New_York",
    "preferences": {
      "optedOut": false,
      "channels": [],
      "quietHours": [
        {
          "start": "22:00",
          "end": "08:00"
        }
      ]
    }
  },
  "destination": "[email protected]",
  "deliveryOptions": {
    "maxAttempts": 3,
    "timeoutMs": 10000
  },
  "renderedContent": {
    "content": {
      "subject": "Order 99214 confirmed",
      "text": "Thanks! Your order 99214 is confirmed.",
      "html": "<p>Thanks! Your order <b>99214</b> is confirmed.</p>"
    }
  }
}

Workflow API

import { workflow } from "notifkit";

workflow("invite", async ({ step, event }) => {
  await step.notify({ template: "invite" });   // no target: the instance's user
  await step.wait("3d");
  const accepted = await step.waitForEvent("invite.accepted", {
    timeout: "24h",
    match: { userId: event.user.id },
  });
  if (!accepted) await step.notify({ template: "invite-reminder", channels: ["sms"] });
});
StepReturns
step.notify(payload){ success, messageId, notificationId }. Takes every notify() field.
step.wait(duration)Nothing. Durations use ms, s, m, h or d.
step.waitForEvent(name, options?)The event's properties, or null on timeout (default 24h).
step.run(name, fn)Whatever fn returns, run once and replayed from storage.

Steps are matched by call order, so make the same step calls on every replay. Register workflows in the process running the workflow service.

Limits

LimitValue
Request body5 MB
API requests per project600 a minute (admin key 6,000)
Messages per user100 an hour (RATE_LIMIT_PER_HOUR)
Segment or topic fan-out100,000 users (SEGMENT_MAX_USERS)
Provider call timeout10 seconds
Delivery attempts3, retried after 30 seconds and 2 minutes
Idempotency key window24 hours
Scheduler and workflow timer pollingEvery 5 seconds