Star
Start here

Examples

Twenty notifications you've received this week, and the code behind each. They build up: send a message, react to an event, wait and branch, then coordinate channels and providers.

You need a running server (the quickstart takes a few minutes), and each example assumes its template is already synced. Both tabs do the same thing: notifkit is a NotifkitClient, and the shell tab is the HTTP under it.

Send a message

Five notifications, one call each. In order, they cover who gets it, on which channels, and whether they can refuse.

1. Order confirmation

What you are building

"Your order #99214 has been confirmed πŸŽ‰", the email Amazon sends the second you check out. One user, one channel, one call.

Copy this

await notifkit.notify({
  user: "usr_9142",
  template: "order-confirmed",
  channels: ["email"],
  data: { orderId: "99214", total: "$349.00", eta: "Friday" },
});
curl -X POST https://notify.example.com/v1/notify \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "user": "usr_9142",
    "template": "order-confirmed",
    "channels": ["email"],
    "data": { "orderId": "99214", "total": "$349.00", "eta": "Friday" }
  }'

What happened

The call returned 202 at once: queued, not delivered. A worker then looked up the address, checked opt-outs, rendered the template with your data, and handed it to your email provider. If the process restarts mid-flight, another worker picks the message up.

Try changing it

  • Swap "email" for "push". Nothing else changes, except that notifkit looks up a device token instead.
  • Pass the user inline: user: { id: "usr_9142", email: "[email protected]" } creates them as part of the send.

2. Login code

What you are building

"Your verification code is 480913. Expires in 5 minutes." Useless in an hour, so it must arrive even at 2am during the user's quiet hours.

Copy this

await notifkit.notify({
  user: "usr_9142",
  template: "login-code",
  channels: ["sms", "email"],
  fallback: true,          // try SMS; only if it fails, email
  priority: "critical",    // ignore quiet hours and throttling
  data: { code: "480913", expiresMinutes: 5 },
});
curl -X POST https://notify.example.com/v1/notify \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "user": "usr_9142",
    "template": "login-code",
    "channels": ["sms", "email"],
    "fallback": true,
    "priority": "critical",
    "data": { "code": "480913", "expiresMinutes": 5 }
  }'

What happened

fallback: true made the channel list an ordered chain, so email goes only if SMS fails. critical skipped quiet hours and the per-user rate limit, and used its own queue so a marketing blast queued a second earlier can't delay it.

3. Package shipped

What you are building

"Your package is on the way. Arriving Friday." The email is the record, the push the reassurance, so you want both, every time.

Copy this

await notifkit.notify({
  user: "usr_9142",
  template: "package-shipped",
  channels: ["email", "push"],     // no fallback: send both
  data: { orderId: "99214", carrier: "UPS", tracking: "1Z999AA10123456784", eta: "Friday" },
});
curl -X POST https://notify.example.com/v1/notify \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "user": "usr_9142",
    "template": "package-shipped",
    "channels": ["email", "push"],
    "data": {
      "orderId": "99214",
      "carrier": "UPS",
      "tracking": "1Z999AA10123456784",
      "eta": "Friday"
    }
  }'

What happened

Each channel is evaluated separately. If the user has push off, the email still goes. The push is dropped and logged with a reason, and no error is raised.

4. Payment received

What you are building

"$1,250.00 has been deposited into your account." Money arriving isn't marketing, so nobody should be able to switch it off. That's set on the template, not the call.

Copy this

// a template with no `topic` is transactional: it cannot be opted out of,
// and it carries no unsubscribe header.
await notifkit.syncTemplates({
  templates: [
    {
      id: "deposit-received",
      channel: "push",
      content: { title: "Money in", text: "{{amount}} from {{sender}} just landed." },
    },
  ],
});

await notifkit.notify({
  user: "usr_9142",
  template: "deposit-received",
  channels: ["push", "email"],
  data: { amount: "$1,250.00", sender: "Stripe Payouts", balance: "$4,318.22" },
});
# a template with no "topic" is transactional: it cannot be opted out of,
# and it carries no unsubscribe header.
curl -X PUT https://notify.example.com/v1/templates \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "templates": [{
      "id": "deposit-received",
      "channel": "push",
      "content": { "title": "Money in", "text": "{{amount}} from {{sender}} just landed." }
    }]
  }'

curl -X POST https://notify.example.com/v1/notify \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "user": "usr_9142",
    "template": "deposit-received",
    "channels": ["push", "email"],
    "data": { "amount": "$1,250.00", "sender": "Stripe Payouts", "balance": "$4,318.22" }
  }'

What happened

The template has no topic, so opt-out gates skip it. Give a template a topic and users can refuse that category. Leave it out and they can't. The same choice decides which mail carries a one-click unsubscribe header, the line mailbox providers care about.

5. New follower

What you are building

"Maya started following you." The opposite: people should be able to switch this off without losing password reset mail.

Copy this

// the template declares what kind of message it is
await notifkit.syncTemplates({
  templates: [
    {
      id: "new-follower",
      channel: "push",
      topic: "social",                                  // refusable
      content: { title: "New follower", text: "{{name}} started following you." },
    },
  ],
});

await notifkit.notify({
  user: followedUserId,
  template: "new-follower",
  channels: ["push"],
  priority: "low",
  data: { name: "Maya", handle: "@maya", avatar: follower.avatarUrl },
});

// and when they switch it off in your settings screen
await notifkit.updateUserPreferences("usr_9142", { topics: { social: false } });
# the template declares what kind of message it is
curl -X PUT https://notify.example.com/v1/templates \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "templates": [{
      "id": "new-follower",
      "channel": "push",
      "topic": "social",
      "content": { "title": "New follower", "text": "{{name}} started following you." }
    }]
  }'

curl -X POST https://notify.example.com/v1/notify \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "user": "usr_8801",
    "template": "new-follower",
    "channels": ["push"],
    "priority": "low",
    "data": { "name": "Maya", "handle": "@maya" }
  }'

# and when they switch it off in your settings screen
curl -X PATCH https://notify.example.com/v1/users/usr_9142/preferences \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "topics": { "social": false } }'

What happened

After that preference change, every later new-follower send to this user is dropped before rendering and logged with a reason. Receipts and password resets still arrive, since those templates have no topic. Topic opt-outs let someone mute one feature instead of muting you entirely.

Try changing it

  • Mute a whole channel instead: { channels: { push: false } }.
  • Give a template two topics: topic: ["social", "marketing"].

React to an event

Still one call, now triggered by something in your product. The details start to matter: which channel is worth paying for, when it should land, and who's listening.

6. Delivery arriving

What you are building

"Your DoorDash order is 2 minutes away." Push is free and instant, so try it first. A dead push token here means a cold dinner, so pay for SMS if push fails.

Copy this

await notifkit.notify({
  user: "usr_9142",
  template: "driver-arriving",
  channels: ["push", "sms"],
  fallback: true,
  priority: "high",
  data: { driver: "Marcus", etaMinutes: 2, trackUrl: "https://app.co/t/99214" },
});
curl -X POST https://notify.example.com/v1/notify \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "user": "usr_9142",
    "template": "driver-arriving",
    "channels": ["push", "sms"],
    "fallback": true,
    "priority": "high",
    "data": { "driver": "Marcus", "etaMinutes": 2, "trackUrl": "https://app.co/t/99214" }
  }'

What happened

Push was tried first. If the token had expired, SMS went out instead. If push landed, the SMS was never sent or billed. high uses a fast queue without overriding quiet hours, which is right: a delivery update is no reason to ignore someone's settings.

Try changing it

  • Go three deep: ["push", "sms", "email"].
  • Turn the user's SMS preference off and the chain stops instead of rolling over: a person declining isn't a delivery failure. See Channels & fallback.

7. Comment reply

What you are building

"Alex replied to your comment: 'This is πŸ”₯'" Triggered by one user, delivered to another, and refusable like any social notification.

Copy this

await notifkit.notify({
  user: parentComment.authorId,          // the person being replied to
  template: "comment-reply",             // template declares topic: "social"
  channels: ["push"],
  priority: "low",
  data: {
    replier: reply.author.handle,
    excerpt: reply.body.slice(0, 120),
    url: reply.url,
  },
});
curl -X POST https://notify.example.com/v1/notify \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "user": "usr_8801",
    "template": "comment-reply",
    "channels": ["push"],
    "priority": "low",
    "data": {
      "replier": "@alex",
      "excerpt": "This is fire",
      "url": "https://app.co/c/91"
    }
  }'

8. Price drop

What you are building

"The Sony headphones you saved dropped from $249 to $199." The audience is everyone watching one product, which is exactly a topic, so you never keep a recipient list.

Copy this

// when someone taps "notify me when the price drops"
await notifkit.updateUserPreferences("usr_9142", {
  topics: { "price-drop:product-123": true },
});

// when the price actually moves, address the topic instead of a person
await notifkit.notify({
  topic: "price-drop:product-123",
  template: "price-drop",
  channels: ["push", "email"],
  data: { name: "Sony WH-1000XM5", was: "$249.00", now: "$199.00" },
});
# when someone taps "notify me when the price drops"
curl -X PATCH https://notify.example.com/v1/users/usr_9142/preferences \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "topics": { "price-drop:product-123": true } }'

# when the price actually moves, address the topic instead of a person
curl -X POST https://notify.example.com/v1/notify \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "topic": "price-drop:product-123",
    "template": "price-drop",
    "channels": ["push", "email"],
    "data": { "name": "Sony WH-1000XM5", "was": "$249.00", "now": "$199.00" }
  }'

9. Calendar reminder

What you are building

"Your meeting with John starts in 15 minutes." You know at booking time when it should fire, so say so once.

Copy this

await notifkit.notify({
  user: "usr_9142",
  template: "meeting-reminder",
  channels: ["push"],
  sendAt: "2026-09-12T16:45:00Z",        // absolute UTC, 15 min before a 17:00 meeting
  data: { with: "John", startsIn: 15, joinUrl: "https://meet.co/abc-defg" },
});

// they cancelled the meeting. find the parked task and drop it.
const { scheduled } = await notifkit.getScheduledMessages();
await notifkit.cancelNotification(scheduled[0].taskId);
curl -X POST https://notify.example.com/v1/notify \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "user": "usr_9142",
    "template": "meeting-reminder",
    "channels": ["push"],
    "sendAt": "2026-09-12T16:45:00Z",
    "data": { "with": "John", "startsIn": 15, "joinUrl": "https://meet.co/abc-defg" }
  }'

# they cancelled the meeting. find the parked task and drop it.
curl -s https://notify.example.com/v1/notifications/scheduled \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY"

curl -X DELETE https://notify.example.com/v1/notifications/{taskId} \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY"

What happened

The message was rendered and parked, and a scheduler released it at the time you named. Cancelling takes a task id, not the notificationId the call returned: one notify() can park many tasks, so find yours with getScheduledMessages(). Once released, there's no recall.

10. Streak reminder

What you are building

"Your 47-day streak ends tonight. Keep it alive!" Duolingo's owl arrives in your evening, not at 19:00 UTC, with no per-user maths and no workflow.

The flow

every hour
    ↓
your database tags whoever's streak is at risk
    ↓
one call to the segment
    ↓
inside someone's quiet hours?  ──YES──▢ deferred to the end of their window
    β”‚ NO
    β–Ό
push goes out now

Copy this

// the SDK takes no idempotency argument, so set the header yourself
await fetch("https://notify.example.com/v1/notify", {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${process.env.NOTIFKIT_API_KEY}`,
    "Content-Type": "application/json",
    "X-Idempotency-Key": "streak-2026-09-07-18",   // the hour this run covers
  },
  body: JSON.stringify({
    segment: "streak-at-risk",
    template: "streak-reminder",
    channels: ["push"],
    priority: "low",
  }),
});
# your own cron, hourly
curl -X POST https://notify.example.com/v1/notify \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY" \
  -H "X-Idempotency-Key: streak-2026-09-07-18" \
  -H "Content-Type: application/json" \
  -d '{
    "segment": "streak-at-risk",
    "template": "streak-reminder",
    "channels": ["push"],
    "priority": "low"
  }'

What happened

Quiet hours did the timezone work. Anyone inside their window wasn't dropped. Their send was deferred to the window's end on their local clock. One call reaches Boston and Los Angeles each in their own evening.

11. Card payment alert

What you are building

"$2,450 spent at ZARA. If this wasn't you, tap here." Your bank pings you the instant the card is used. You want push and SMS, not whichever works first.

Copy this

await notifkit.notify({
  user: "usr_9142",
  template: "card-charged",
  channels: ["push", "sms"],       // deliberately NO fallback: send both
  priority: "critical",
  data: {
    amount: "$2,450.00",
    merchant: "ZARA",
    city: "Chicago, IL",
    disputeUrl: "https://bank.co/dispute/tx_5512",
  },
});
curl -X POST https://notify.example.com/v1/notify \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "user": "usr_9142",
    "template": "card-charged",
    "channels": ["push", "sms"],
    "priority": "critical",
    "data": {
      "amount": "$2,450.00",
      "merchant": "ZARA",
      "city": "Chicago, IL",
      "disputeUrl": "https://bank.co/dispute/tx_5512"
    }
  }'

What happened

Compare the login code: same two channels, same critical priority, opposite outcome, because that one had fallback. For possible fraud, a duplicate costs nothing and a missed alert costs real money.

12. Flight delay

What you are building

"Your flight to Denver is delayed 45 minutes." Like the card alert, but their phone may have no data, so email is in the mix too.

Copy this

await notifkit.notify({
  user: "usr_9142",
  template: "flight-delayed",
  channels: ["push", "sms", "email"],   // all three, no fallback
  priority: "critical",
  data: {
    flight: "UA 2043",
    destination: "Denver",
    delayMinutes: 45,
    newDeparture: "6:15 PM",
    gate: "C12",
  },
});
curl -X POST https://notify.example.com/v1/notify \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "user": "usr_9142",
    "template": "flight-delayed",
    "channels": ["push", "sms", "email"],
    "priority": "critical",
    "data": {
      "flight": "UA 2043",
      "destination": "Denver",
      "delayMinutes": 45,
      "newDeparture": "6:15 PM",
      "gate": "C12"
    }
  }'

Try changing it

  • Reach everyone on the flight: tag them into a segment at check-in, then send to segment: "flight-ua2043".
  • Add campaign: "irrops-2026-09-12" to report how many passengers you reached during a disruption.

Wait for something, then branch

So far, everything is one call. What follows takes hours or days, so it needs somewhere to live between steps. A workflow is a normal async function whose awaits can last three days and survive a deploy, because each finished step is written to Postgres before the next runs.

CallWhat it does
step.wait("45m")Sleeps. Nothing is held in memory, and the instance is woken later.
step.waitForEvent(name, opts)Sleeps until your app reports something happened, or the timeout fires. Returns the event, or null on timeout.
step.notify(payload)Sends. Takes every field notify() takes.
step.run(name, fn)Runs your own code once and remembers the result, so a database read does not repeat on every replay.

13. Abandoned cart

What you are building

"Still thinking about those sneakers?" The hard part is staying silent when they've already bought.

The flow

cart abandoned
      ↓
 wait 45 minutes
      ↓
 did they order within 6 hours?
   β”Œβ”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”
  YES            NO
   ↓              ↓
 STOP        send the reminder
             (push, email if push fails)

Copy this

workflow("cart-reminder", async ({ step, event }) => {
  await step.wait("45m");

  const ordered = await step.waitForEvent("order.placed", {
    timeout: "6h",
    match: { cartId: event.cartId },
  });

  if (ordered) return;                 // they bought. say nothing.

  await step.notify({
    template: "cart-reminder",
    channels: ["push", "email"],
    fallback: true,
    data: { items: event.items, cartUrl: event.cartUrl },
  });
});
# when the cart goes quiet, start an instance
curl -X POST https://notify.example.com/v1/workflows/trigger \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "cart-reminder",
    "user": "usr_9142",
    "input": {
      "cartId": "cart_771",
      "items": ["Nike Pegasus 41"],
      "cartUrl": "https://shop.co/cart/771"
    }
  }'

# later, when they check out, this wakes the instance and cancels the nudge
curl -X POST https://notify.example.com/v1/events \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "order.placed",
    "properties": { "cartId": "cart_771", "userId": "usr_9142" }
  }'

What happened

The instance slept 45 minutes, then suspended again waiting for an event that might never come. Nothing ran during either wait. Posting order.placed with a matching cartId woke it, ordered came back as the event payload, and the function returned without sending anything.

14. Abandoned cart, then a discount

What you are building

"10% off your cart, today only." A second stage, only if the plain reminder failed. Leading with the discount teaches people to abandon carts on purpose.

The flow

cart abandoned β†’ wait 45m β†’ bought within 6h? ──YES──▢ STOP
                                  β”‚ NO
                                  β–Ό
                          send plain reminder
                                  ↓
                             wait 24 hours
                                  ↓
                          bought within 24h? ──YES──▢ STOP
                                  β”‚ NO
                                  β–Ό
                          send 10% discount code

Copy this

workflow("cart-recovery", async ({ step, event }) => {
  await step.wait("45m");

  const boughtEarly = await step.waitForEvent("order.placed", {
    timeout: "6h",
    match: { cartId: event.cartId },
  });
  if (boughtEarly) return;

  await step.notify({
    template: "cart-reminder",
    channels: ["push"],
    data: { items: event.items },
  });

  await step.wait("24h");

  const boughtLate = await step.waitForEvent("order.placed", {
    timeout: "24h",
    match: { cartId: event.cartId },
  });
  if (boughtLate) return;

  await step.notify({
    template: "cart-discount",
    channels: ["email"],
    data: { items: event.items, code: "SAVE10", expiresHours: 24 },
  });
});
curl -X POST https://notify.example.com/v1/workflows/trigger \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "cart-recovery",
    "user": "usr_9142",
    "input": { "cartId": "cart_771", "items": ["Nike Pegasus 41"] }
  }'

# either checkout event ends the run, whichever stage it is in
curl -X POST https://notify.example.com/v1/events \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "name": "order.placed", "properties": { "cartId": "cart_771" } }'

15. Trial onboarding

What you are building

The first week of Notion or Figma: a sequence that continues only while you're not getting on with it. Any stage can end it.

The flow

day 0  welcome                      always sent
   ↓
day 1  finished the first task?     yes ─▢ skip the nudge
       no  ─▢ "it takes 3 minutes"
   ↓
day 3  come back at all?            yes ─▢ celebrate, STOP
       no  ─▢ "try a smaller goal?"
   ↓
day 7  still nothing?               yes ─▢ STOP bothering them
                                    no  ─▢ tag them for the win-back segment

Copy this

workflow("trial-onboarding", async ({ step, event }) => {
  const uid = event.userId;

  await step.notify({ template: "welcome", channels: ["email"] });

  await step.wait("1d");

  const startedDay1 = await step.waitForEvent("project.created", {
    timeout: "1d",
    match: { userId: uid },
  });
  if (!startedDay1) {
    await step.notify({
      template: "first-project-nudge",
      channels: ["email", "push"],
      fallback: true,
      data: { minutes: 3 },
    });
  }

  await step.wait("2d");

  const startedDay3 = await step.waitForEvent("project.created", {
    timeout: "2d",
    match: { userId: uid },
  });
  if (startedDay3) {
    await step.notify({ template: "activation-congrats", channels: ["push"], priority: "low" });
    return;                                   // they are onboarded. stop here.
  }

  await step.notify({
    template: "smaller-goal",
    channels: ["email"],
    data: { suggestion: "Start with a single page" },
  });

  await step.wait("4d");

  const startedDay7 = await step.waitForEvent("project.created", {
    timeout: "4d",
    match: { userId: uid },
  });
  if (startedDay7) return;

  // hand them over to the win-back campaign and stop sending onboarding mail
  await step.run("mark-dormant", async () => {
    await db.users.tag(uid, "never-activated");
  });
});
# start it from your signup handler
curl -X POST https://notify.example.com/v1/workflows/trigger \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "trial-onboarding",
    "user": { "id": "usr_9142", "email": "[email protected]" },
    "input": { "userId": "usr_9142", "plan": "pro-trial" }
  }'

# every time they do the thing that matters, post it. any stage can exit on it.
curl -X POST https://notify.example.com/v1/events \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "name": "project.created", "properties": { "userId": "usr_9142" } }'

What happened

Only the if bodies differ between runs, so the workflow replays safely. The final step.run tags the user so a later segment send can reach them.

16. Failed payment recovery

What you are building

"Your payment failed. We'll retry automatically tomorrow." Then the ladder every subscription business runs, ending with your billing team hearing about it before the account suspends.

The flow

payment failed
      ↓
polite email ─────────────────────────── day 0
      ↓
wait 72h  (the card network retries in here)
      ↓
paid? ──YES──▢ "thanks, sorted" ──▢ STOP
  β”‚ NO
  β–Ό
urgent SMS + email ───────────────────── day 3
      ↓
wait 48h
      ↓
paid? ──YES──▢ "thanks, sorted" ──▢ STOP
  β”‚ NO
  β–Ό
alert #billing-ops in Slack ──────────── day 5
      ↓
final notice to the customer

Copy this

workflow("recover-payment", async ({ step, event }) => {
  await step.notify({
    template: "payment-failed-soft",
    channels: ["email"],
    data: { amount: event.amount, invoiceUrl: event.invoiceUrl },
  });

  await step.wait("72h");

  const paidAfterRetry = await step.waitForEvent("invoice.paid", {
    timeout: "48h",
    match: { customerId: event.customerId },
  });
  if (paidAfterRetry) {
    await step.notify({ template: "payment-recovered", channels: ["email"] });
    return;
  }

  await step.notify({
    template: "payment-urgent",
    channels: ["sms", "email"],
    fallback: true,
    priority: "high",
    data: { amount: event.amount, suspendsOn: event.periodEnd },
  });

  await step.wait("48h");

  const paidAfterSms = await step.waitForEvent("invoice.paid", {
    timeout: "24h",
    match: { customerId: event.customerId },
  });
  if (paidAfterSms) {
    await step.notify({ template: "payment-recovered", channels: ["email"] });
    return;
  }

  // your team, not the customer. different audience, different channel.
  await step.notify({
    topic: "billing-ops",
    template: "churn-risk",
    channels: ["slack"],
    priority: "high",
    data: { customerId: event.customerId, mrr: event.amount, daysOverdue: 5 },
  });

  await step.notify({ template: "final-notice", channels: ["email"], priority: "high" });
});
# from your Stripe webhook handler on invoice.payment_failed
curl -X POST https://notify.example.com/v1/workflows/trigger \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "recover-payment",
    "user": "usr_9142",
    "input": {
      "customerId": "cus_M4x",
      "amount": "$49.00",
      "invoiceUrl": "https://billing.co/i/8812",
      "periodEnd": "2026-09-12"
    }
  }'

# and on invoice.payment_succeeded, which ends the run at whichever rung it is on
curl -X POST https://notify.example.com/v1/events \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "name": "invoice.paid", "properties": { "customerId": "cus_M4x" } }'

What happened

Two audiences in one workflow. Customer messages name no target, so they go to the instance's user. The Slack message names topic: "billing-ops", so it reaches whoever subscribes to that topic, and your billing code never needs to know who's on the rota.

17. Subscription cancellation rescue

What you are building

Cancel Netflix and it confirms, then a couple of days later tells you what you're missing. Change your mind first and nothing commercial is sent.

The flow

user cancels
      ↓
send cancellation confirmation
      ↓
   wait 1 hour
      ↓
did they resume?
 β”Œβ”€β”€β”€β”€β”΄β”€β”€β”€β”€β”
YES        NO
 ↓          ↓
STOP   send the win-back offer
            ↓
       wait 48 hours
            ↓
      resumed by now?
      β”Œβ”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”
     YES          NO
      ↓            ↓
"welcome back"  ask why they left

Copy this

workflow("cancellation-rescue", async ({ step, event }) => {
  // 1. always confirm. transactional, so the template carries no topic.
  await step.notify({
    template: "cancellation-confirmed",
    channels: ["email"],
    data: { accessUntil: event.periodEnd, plan: event.plan },
  });

  await step.wait("1h");

  // 2. a change of heart in the first hour is common. do not sell to them.
  const changedMind = await step.waitForEvent("subscription.resumed", {
    timeout: "1h",
    match: { customerId: event.customerId },
  });
  if (changedMind) return;

  // 3. pick the offer from what they actually used, once, not on every replay
  const offer = await step.run("choose-offer", async () => {
    const usage = await billing.usageFor(event.customerId);
    return usage.hoursLastMonth > 20
      ? { discount: "50%", months: 3 }
      : { discount: "30%", months: 2 };
  });

  await step.notify({
    template: "winback-offer",
    channels: ["email", "push"],
    fallback: true,
    data: offer,
  });

  await step.wait("48h");

  const cameBack = await step.waitForEvent("subscription.resumed", {
    timeout: "48h",
    match: { customerId: event.customerId },
  });
  if (cameBack) {
    await step.notify({ template: "welcome-back", channels: ["email"] });
    return;
  }

  await step.notify({ template: "exit-survey", channels: ["email"], priority: "low" });
});
curl -X POST https://notify.example.com/v1/workflows/trigger \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "cancellation-rescue",
    "user": "usr_9142",
    "input": {
      "customerId": "cus_M4x",
      "plan": "Standard",
      "periodEnd": "2026-10-01"
    }
  }'

# posting this at any point ends the run early
curl -X POST https://notify.example.com/v1/events \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "name": "subscription.resumed", "properties": { "customerId": "cus_M4x" } }'

What happened

Three exits, two before anything commercial goes out. step.run keeps the billing lookup honest: the body reruns from the top on every wake, but that block executes once and replays its stored result, so your billing service isn't hit four times over three days.

Coordinate channels and providers

The last three combine everything: waiting on a human, reaching thousands without delaying anyone's login code, and staying up when a provider goes down.

18. Escalate when they ignore it

What you are building

WhatsApp pings your phone. If you still haven't read it, you get an email. The push arrived fine. The question is whether the person did anything.

The flow

message arrives for an offline user
            ↓
        send push
            ↓
   opened the app within 20m? ──YES──▢ STOP
            β”‚ NO
            β–Ό
        send email
            ↓
   opened within 2 hours? ──YES──▢ STOP
            β”‚ NO
            β–Ό
   SMS, but only if the sender marked it urgent

Copy this

workflow("unread-escalation", async ({ step, event }) => {
  await step.notify({
    template: "new-message",
    channels: ["push"],
    data: { from: event.senderName, preview: event.preview },
  });

  const openedSoon = await step.waitForEvent("thread.opened", {
    timeout: "20m",
    match: { threadId: event.threadId, userId: event.userId },
  });
  if (openedSoon) return;

  await step.notify({
    template: "unread-message",
    channels: ["email"],
    data: { from: event.senderName, preview: event.preview, url: event.threadUrl },
  });

  const openedLater = await step.waitForEvent("thread.opened", {
    timeout: "2h",
    match: { threadId: event.threadId, userId: event.userId },
  });
  if (openedLater) return;

  if (event.urgent) {
    await step.notify({ template: "unread-urgent", channels: ["sms"], priority: "high" });
  }
});
# when a message arrives for someone who is offline
curl -X POST https://notify.example.com/v1/workflows/trigger \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "unread-escalation",
    "user": "usr_9142",
    "input": {
      "threadId": "thr_88",
      "userId": "usr_9142",
      "senderName": "Alex",
      "preview": "are we still on for 6?",
      "threadUrl": "https://app.co/t/88",
      "urgent": false
    }
  }'

# wherever a thread gets opened in your app
curl -X POST https://notify.example.com/v1/events \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "thread.opened",
    "properties": { "threadId": "thr_88", "userId": "usr_9142" }
  }'

19. Service outage broadcast

What you are building

"Checkout is currently unavailable. We'll update you when it's fixed." It goes to many people at once, and must not delay anyone's login code.

Copy this

await notifkit.notify({
  segment: "active-last-24h",
  template: "service-degraded",
  channels: ["email"],
  priority: "low",                       // its own lane, behind everything transactional
  campaign: "incident-2026-09-12",
  data: { service: "Checkout", statusUrl: "https://status.example.com" },
});

// when it is fixed, same segment, same campaign label
await notifkit.notify({
  segment: "active-last-24h",
  template: "service-restored",
  channels: ["email"],
  priority: "low",
  campaign: "incident-2026-09-12",
  data: { service: "Checkout", downtimeMinutes: 39 },
});
curl -X POST https://notify.example.com/v1/notify \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "segment": "active-last-24h",
    "template": "service-degraded",
    "channels": ["email"],
    "priority": "low",
    "campaign": "incident-2026-09-12",
    "data": { "service": "Checkout", "statusUrl": "https://status.example.com" }
  }'

# when it is fixed, same segment, same campaign label
curl -X POST https://notify.example.com/v1/notify \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "segment": "active-last-24h",
    "template": "service-restored",
    "channels": ["email"],
    "priority": "low",
    "campaign": "incident-2026-09-12",
    "data": { "service": "Checkout", "downtimeMinutes": 39 }
  }'

What happened

The server expanded the segment into one message per person, all on the low lane. Priorities are separate streams, so a hundred thousand queued emails can't sit in front of a critical send. Each message is still gated individually: anyone who opted out of the topic gets nothing.

20. On-call incident, and provider failover

What you are building

"SEV-1: checkout-api error rate is 31%. Acknowledge now." The one message here meant to ignore everything: sent to a rota, not a person, and escalating if nobody answers. Underneath, the setup that keeps mail moving when your email provider is the one down.

The flow

SEV-1 detected
      ↓
page primary on-call  ──── acknowledged in 5m? ──YES──▢ STOP
      β”‚ NO
      β–Ό
page secondary + #incidents ── acked in 5m? ──YES──▢ STOP
      β”‚ NO
      β–Ό
page the engineering manager

every page goes to push AND sms AND slack.
NO FALLBACK: you want all three, not whichever lands first.

Copy this

workflow("incident-escalation", async ({ step, event }) => {
  const page = {
    severity: event.severity,
    summary: event.summary,
    runbook: event.runbook,
  };

  await step.notify({
    topic: "oncall-primary",
    template: "incident-page",
    channels: ["push", "sms", "slack"],   // no fallback: wake them on all three
    priority: "critical",
    data: page,
  });

  const ackedByPrimary = await step.waitForEvent("incident.acknowledged", {
    timeout: "5m",
    match: { incidentId: event.incidentId },
  });
  if (ackedByPrimary) return;

  await step.notify({
    topic: "oncall-secondary",
    template: "incident-page",
    channels: ["push", "sms", "slack"],
    priority: "critical",
    data: { ...page, escalation: 1 },
  });

  const ackedBySecondary = await step.waitForEvent("incident.acknowledged", {
    timeout: "5m",
    match: { incidentId: event.incidentId },
  });
  if (ackedBySecondary) return;

  await step.notify({
    topic: "engineering-managers",
    template: "incident-page",
    channels: ["push", "sms", "slack"],
    priority: "critical",
    data: { ...page, escalation: 2 },
  });
});
# from your alerting rule
curl -X POST https://notify.example.com/v1/workflows/trigger \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "incident-escalation",
    "input": {
      "incidentId": "inc_5512",
      "severity": "SEV-1",
      "summary": "checkout-api error rate 31%, p99 8.4s",
      "runbook": "https://wiki.internal/runbooks/checkout"
    }
  }'

# when someone hits acknowledge
curl -X POST https://notify.example.com/v1/events \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "name": "incident.acknowledged", "properties": { "incidentId": "inc_5512" } }'

What happened

Every page is deliberately a multicast. At 3am you want push, SMS and Slack: three notifications cost nothing next to a missed page. Addressing a topic means the rota owns who's subscribed this week, and your alerting code never needs to know.

Now the layer underneath

None of that helps if your email provider is down. Register a second transport on the same channel and the delivery worker uses it when the first fails. No call site changes.

import { registerTransport } from "notifkit";
import { ResendTransport } from "@notifkit/provider-resend";
import { SesTransport } from "./transports/ses.js";   // one you wrote

// higher number is tried first
registerTransport(new ResendTransport({ apiKey: process.env.RESEND_KEY!, from: "[email protected]" }), 10);
registerTransport(new SesTransport({ region: "us-east-1", from: "[email protected]" }), 5);
# transports are server boot config, so there is no HTTP call to register one.
# what you can check over HTTP is what happened to a message afterwards:
curl -s https://notify.example.com/v1/notifications/{taskId} \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY"

# every attempt, which provider took it, and the response it gave
curl -s "https://notify.example.com/v1/notifications/logs?limit=20" \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY"
Resend saysWhat happens next
DeliveredDone. SES is never called and never billed.
503, timeout, or throwsSES is tried with the same rendered message.
Both failThe email channel is exhausted. If the call named a next channel with fallback, it rolls over. Otherwise a failed row lands in the delivery log.
429, rate limitedSES is tried, since Resend is busy, not down. If SES has no room either, the message waits for it without using up maxAttempts. After 15 minutes of waiting, the channel counts as exhausted and the chain moves on.

Checking what happened

Every call here returns 202, which only means queued. This is how you find out whether anything arrived.

// one message, end to end: every attempt, provider response and timing
const { status, logs } = await notifkit.getNotificationStatus(taskId);

// a whole campaign
const { totals, warnings } = await notifkit.getCampaignStats("incident-2026-09-12");

// why did this person get nothing? usually the answer is here.
const { suppressions } = await notifkit.listSuppressions({ target: "[email protected]" });

// what is parked and waiting to go out later
const { scheduled } = await notifkit.getScheduledMessages();
# one message, end to end
curl -s https://notify.example.com/v1/notifications/{taskId} \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY"

# a whole campaign
curl -s https://notify.example.com/v1/campaigns/incident-2026-09-12/stats \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY"

# why did this person get nothing?
curl -s "https://notify.example.com/v1/[email protected]" \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY"

# what is parked and waiting
curl -s https://notify.example.com/v1/notifications/scheduled \
  -H "Authorization: Bearer $NOTIFKIT_API_KEY"

Runnable versions of the basics are in the repository's examples folder.