Channel examples

Channel examples

One complete, copyable example per channel (email over SES or Cloudflare, APNs, FCM, Web Push, Slack, Discord, push-else-email, and SMS through a custom action), from the secrets it needs to what you see once it is sent.

This page is a cookbook: one end-to-end example per channel, each in the same order. First what the channel needs configured, then the template, its registration, the step that sends it, how the recipient is found, what you see once it is sent, and the pitfalls. The reasoning behind templates, topics and opt-outs is on Templates and channels, what happens when a send fails is on Delivery, and every step is described on Steps.

The shared contract

Every example below reads this contract. Profile fields feed props through u, and the triggering event's payload feeds them through the trigger handle (see Reading the triggering event).

ts
// src/contract.ts
import { defineContract, templatesFor } from 'sendwend';
import {
  email,
  looseObject,
  number,
  optional,
  strictObject,
  string,
} from 'zod/mini';

export const contract = defineContract({
  events: {
    sign_up: looseObject({ method: string() }),
    order_placed: looseObject({
      order_id: string(),
      total: number(),
      currency: string(),
    }),
    order_shipped: looseObject({ order_id: string(), carrier: string() }),
    subscription_canceled: looseObject({
      plan: string(),
      reason: optional(string()),
    }),
    // What a browser's notification tap is also recorded as (webPush.openedEvent)
    push_opened: looseObject({ message_id: string() }),
  },
  profile: strictObject({
    email: optional(email()),
    name: string(),
    phone: optional(string()),
  }),
  subscriptions: { topics: ['tips'] },
});

export const e = contract.events;
export const u = contract.user;
export const { emailTemplate, pushTemplate } = templatesFor(contract);

All templates end up in one registry, and the config registers it once:

ts
// src/templates.ts
import { discord } from './discord';
import { email } from './email';
import { push } from './push';
import { slack } from './slack';

export const templates = { email, push, slack, discord };
ts
// workflow.config.ts
import { defineConfig } from 'sendwend';
import { sendShippingSms } from './src/actions';
import { contract } from './src/contract';
import { templates } from './src/templates';
import { workflows } from './src/workflows';

export default defineConfig({
  contract,
  workflows,
  templates,
  actions: [sendShippingSms],
  email: {
    unsubscribeUrl: 'https://acme.test/unsubscribe',
    preferencesUrl: 'https://acme.test/settings/email',
  },
  apns: { topic: 'com.acme.app', keyId: 'ABC123DEFG', teamId: 'TEAM123456' },
  fcm: { androidChannelId: 'journeys' },
  webPush: { subject: 'mailto:support@acme.test', openedEvent: 'push_opened' },
  runtime: { development: { timeScale: 600, logMessages: true } },
});

logMessages: true echoes every outbound copy to the log before it is sent, which is what the "what you see" parts below show. The host itself is covered per runtime on Cloudflare, AWS Lambda and self-hosting; only the parts each channel adds are shown here.

Email

Configure. A transport, passed as the host's email option (one of the three below), and a sender domain the provider has verified. With Postgres reporting and an https WORKFLOW_ORIGIN, links and opens are tracked and the topic email gets a one-click List-Unsubscribe header; without them the email still goes out. A host whose workflows send email but that has no email option fails when it is created, naming those workflows.

Templates. Each template names its own from; there is no global sender, so share addresses through a module. The layout reads the unsubscribe and preference links from the render context, so one layout serves a transactional email (no links) and a topic email (both links):

tsx
// src/email/senders.ts
export const senders = {
  hello: { email: 'hello@acme.test', name: 'Acme' },
};
tsx
// src/email/layout.tsx
import { Body, Container, Html, Link, Text } from '@react-email/components';
import type { ReactNode } from 'react';
import { useEmailContext } from 'sendwend/email-context';

export function Layout({ children }: { children: ReactNode }) {
  const { unsubscribeUrl, preferencesUrl, topic } = useEmailContext();
  return (
    <Html>
      <Body>
        <Container>
          {children}
          {topic !== null && (
            <Text>You get these because you subscribed to {topic}.</Text>
          )}
          {preferencesUrl !== undefined && (
            <Link href={preferencesUrl}>Email preferences</Link>
          )}
          {unsubscribeUrl !== undefined && (
            <Link href={unsubscribeUrl}>Unsubscribe</Link>
          )}
        </Container>
      </Body>
    </Html>
  );
}
tsx
// src/email/order-receipt.tsx
import { Text } from '@react-email/components';
import { number, strictObject, string } from 'zod/mini';
import { emailTemplate } from '../contract';
import { Layout } from './layout';
import { senders } from './senders';

export default emailTemplate({
  id: 'order_receipt',
  transactional: true, // sent whatever the user opted out of; no unsubscribe link
  from: senders.hello,
  title: 'Order receipt',
  props: strictObject({
    name: string(),
    orderId: string(),
    total: number(),
    currency: string(),
  }),
  subject: 'Your Acme order',
  preview: { name: 'John Doe', orderId: 'o_1042', total: 49, currency: 'EUR' },
  component: ({ name, orderId, total, currency }) => (
    <Layout>
      <Text>
        Thanks, {name}. Order {orderId} is confirmed: {total} {currency}.
      </Text>
    </Layout>
  ),
});
tsx
// src/email/weekly-tip.tsx
import { Text } from '@react-email/components';
import { emailTemplate } from '../contract';
import { tipProps } from '../tip-props';
import { Layout } from './layout';
import { senders } from './senders';

export default emailTemplate({
  id: 'weekly_tip',
  topic: 'tips', // skipped while the user opted out of tips, or of all email
  from: senders.hello,
  title: 'Weekly tip',
  props: tipProps,
  subject: 'One thing to try this week',
  preview: { name: 'John Doe' },
  component: ({ name }) => (
    <Layout>
      <Text>{name}, pin the projects you open every day.</Text>
    </Layout>
  ),
});
ts
// src/tip-props.ts: shared by the tip email and the tip push, which .prefer() requires
import { strictObject, string } from 'zod/mini';

export const tipProps = strictObject({ name: string() });

Register.

ts
// src/email/index.ts
import orderReceipt from './order-receipt';
import weeklyTip from './weekly-tip';

export const email = { orderReceipt, weeklyTip };

Send. The receipt takes its order fields from the event that started the journey and the name from the profile:

ts
// src/workflows/order-follow-up.ts
import { trigger, workflow } from 'sendwend';
import { e, u } from '../contract';
import { email } from '../email';

const placed = trigger.event(e.order_placed);

export const orderFollowUp = workflow({
  id: 'order_follow_up',
  reentry: { mode: 'concurrent' },
  trigger: placed,
})
  .email(email.orderReceipt, {
    name: u.name,
    orderId: placed.payload.order_id,
    total: placed.payload.total,
    currency: placed.payload.currency,
  })
  .delay('3 days')
  .email(email.weeklyTip, { name: u.name });

Recipient. The profile's email property, read when the step runs. A user without one gets no email: the copy is settled undelivered as no_recipient (or invalid_recipient for a value that is not a bare user@host), and the journey goes on. Report the profile and the event in one ingest call so the address is there before the journey starts (see Sending events).

What you see. In development, with logMessages:

text
[journey] email order_receipt → ada@acme.test {"name":"Ada","orderId":"o_1042","total":49,"currency":"EUR"}

With Postgres, each copy is a row of message, settled with delivered_at (the transport accepted it) or undelivered_reason:

sql
SELECT template, channel, topic, sent_at, delivered_at, undelivered_reason
FROM workflow.message WHERE user_id = 'u_123' ORDER BY sent_at DESC;

A topic email opted out of leaves no row: it was skipped before a copy existed. Studio renders every email template from its preview props, with its From, Reply to, Subject and unsubscribe link above it (Studio views), and the host serves GET /preview/order_receipt?props=<JSON> (with the API bearer), the subject percent-encoded in the x-subject header.

Pitfalls.

  • No email on the profile is no_recipient, not an error: watch that reason in the report rather than waiting for a failed instance.
  • The List-Unsubscribe header names only https URLs, so a local http:// origin sends none. Test one-click unsubscribe on a deployed host.
  • preferencesUrl must not share its origin and path with an unsubscribe URL; the config refuses one that does. See Unsubscribe and preference links.

Amazon SES

sesEmailTransport from sendwend/transports/ses calls the SES v2 SendEmail API with a SigV4 signature over plain fetch, so it runs in a Worker, a Lambda and Node alike. Options: region, credentials (fixed values or a function read on every send), configurationSetName and endpoint.

On AWS Lambda, leave credentials out: the transport reads AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and AWS_SESSION_TOKEN at send time, the function's execution role, which needs ses:SendEmail:

ts
// src/handler.ts (AWS Lambda)
import { journeyLambda } from 'sendwend/aws';
import { postgresJsStore } from 'sendwend/postgres-js';
import { sesEmailTransport } from 'sendwend/transports/ses';
import config from '../workflow.config';
import { env } from './env.aws'; // process.env, parsed: see AWS Lambda

const journeys = journeyLambda({
  config,
  env,
  store: (env, database) => postgresJsStore(env.DATABASE_URL, database),
  email: (env) => sesEmailTransport({ region: env.AWS_REGION }),
});

export const handler = journeys.handler;

A Worker has no execution role, so it passes the keys from its validated environment:

ts
email: (env) =>
  sesEmailTransport({
    region: 'eu-west-1',
    credentials: { accessKeyId: env.AWS_ACCESS_KEY_ID, secretAccessKey: env.AWS_SECRET_ACCESS_KEY },
    configurationSetName: 'journeys', // optional: event publishing, a dedicated IP pool
  }),

A refusal settles under SES's own error code (MessageRejected, for example); throttling (TooManyRequestsException, Throttling, and the rest of the AWS SDK's retryable set) and 5xx are retried. SES takes no idempotency key, so a request it never answered settles as no_answer and is not sent again (Delivery). Mailbox providers honor List-Unsubscribe only when DKIM signs it; check one real message, as AWS Lambda describes.

Cloudflare Email Sending

cloudflareEmailTransport from sendwend/transports/cloudflare-email takes either a Worker's send_email binding or an account id and API token for the REST API, which works from anywhere:

jsonc
// wrangler.jsonc
{ "send_email": [{ "name": "EMAIL" }] }
ts
// src/index.ts (Cloudflare Worker)
import { type JourneyEnv, journeyWorker } from 'sendwend/cloudflare';
import { postgresJsStore } from 'sendwend/postgres-js';
import { cloudflareEmailTransport } from 'sendwend/transports/cloudflare-email';
import config from '../workflow.config';
import { env } from './env';

interface Env extends JourneyEnv {
  HYPERDRIVE: { connectionString: string };
  EMAIL: NonNullable<JourneyEnv['EMAIL']>;
}

const journeys = journeyWorker<Env>({
  config,
  store: (env, database) =>
    postgresJsStore(env.HYPERDRIVE.connectionString, database),
  email: (env) => cloudflareEmailTransport({ binding: env.EMAIL }),
  env,
});

export const AcmeJourneyRunner = journeys.Runner;
export default { fetch: journeys.fetch, scheduled: journeys.scheduled };
ts
// Anywhere else (Node, Lambda): the REST API
email: () => cloudflareEmailTransport({ accountId: process.env.CF_ACCOUNT_ID!, apiToken: process.env.CF_EMAIL_TOKEN! }),

Under wrangler dev the binding only simulates sending and writes the rendered email to a file. A REST refusal settles as cloudflare_<code> (Cloudflare's first error code) or Refused<status>; a REST request that got no answer settles as no_answer. What the binding throws is taken as a refusal and retried, because the binding does not say whether the email left. Cloudflare rejects a List-Unsubscribe header with a non-TLS URI, which is one more reason the header needs an https WORKFLOW_ORIGIN (Cloudflare).

Another provider

The email channel is split where the provider starts to matter: EmailSender renders the template, applies tracking, commits the tracked links and hands a finished EmailMessage (from, to, replyTo?, subject, html, headers?, idempotencyKey) to an EmailTransport. Any object with that one send method is a transport:

ts
// src/mail-transport.ts
import { mimeAddress } from 'sendwend';
import type { EmailTransport } from 'sendwend/email-sender';
import {
  PermanentError,
  awaitAnswer,
  isRetryableStatus,
} from 'sendwend/engine';

export function mailProviderTransport(apiKey: string): EmailTransport {
  return {
    async send(message) {
      // A request that never got an answer throws UnansweredSendError: settled as no_answer, not resent
      const response = await awaitAnswer('mail provider', () =>
        fetch('https://api.mail-provider.example/send', {
          method: 'POST',
          headers: {
            authorization: `Bearer ${apiKey}`,
            'content-type': 'application/json',
            // Stable across retries and replays: pass it if your provider de-duplicates on a key
            'idempotency-key': message.idempotencyKey,
          },
          body: JSON.stringify({
            from: mimeAddress(message.from),
            to: message.to,
            reply_to:
              message.replyTo === undefined
                ? undefined
                : mimeAddress(message.replyTo),
            subject: message.subject,
            html: message.html,
            headers: message.headers, // List-Unsubscribe and List-Unsubscribe-Post, when present
          }),
        })
      );
      if (response.ok) {
        const { id } = (await response.json().catch(() => ({}))) as {
          id?: string;
        };
        return id === undefined ? {} : { providerMessageId: id };
      }
      // 408, 429 and 5xx: throw a plain error and the step retries
      if (isRetryableStatus(response.status))
        throw new Error(`mail provider: ${response.status}`);
      // Anything else is a refusal: the copy settles under this reason and the journey goes on
      throw new PermanentError(`mail provider refused: ${response.status}`, {
        reason: `Refused${response.status}`,
      });
    },
  };
}
ts
email: (env) => mailProviderTransport(env.MAIL_PROVIDER_KEY),

Resolving means the provider accepted the email. A thrown error is classified by what it carries: a reason string names the refusal, retryable: false or a PermanentError makes it permanent, and unanswered: true (or UnansweredSendError) marks a request with no answer (Delivery).

Push

Configure. Each platform is turned on by its config entry, with its secret in the environment. A secret is read only when something is sent on that platform, so a journey that only emails does not need the APNs key in a local .dev.vars. A platform a device registered for but the config does not turn on settles that copy as not_configured.

Templates. One push template serves all three platforms. content(props) returns { title, body, image?, url? }, synchronously, with final text:

ts
// src/push/order-shipped.ts
import { strictObject, string } from 'zod/mini';
import { pushTemplate } from '../contract';

export default pushTemplate({
  id: 'order_shipped_push',
  transactional: true,
  title: 'Order shipped (push)',
  props: strictObject({ name: string(), orderId: string(), carrier: string() }),
  preview: { name: 'John Doe', orderId: 'o_1042', carrier: 'DHL' },
  content: ({ name, orderId, carrier }) => ({
    title: 'Your order is on its way',
    body: `${name}, order ${orderId} left with ${carrier}.`,
    url: `https://acme.test/orders/${orderId}`, // the page a browser push opens
  }),
});
ts
// src/push/weekly-tip.ts
import { pushTemplate } from '../contract';
import { tipProps } from '../tip-props';

export default pushTemplate({
  id: 'weekly_tip_push',
  topic: 'tips',
  title: 'Weekly tip (push)',
  props: tipProps,
  preview: { name: 'John Doe' },
  content: ({ name }) => ({
    title: 'A tip for this week',
    body: `${name}, pin the projects you open every day.`,
  }),
});

Register.

ts
// src/push/index.ts
import orderShipped from './order-shipped';
import weeklyTip from './weekly-tip';

export const push = { orderShipped, weeklyTip };

Send. One copy per device the user has, or only the most recently registered one with { devices: 'latest' }:

ts
// src/workflows/order-shipped.ts
import { trigger, workflow } from 'sendwend';
import { e, u } from '../contract';
import { push } from '../push';

const shipped = trigger.event(e.order_shipped);

export const orderShipped = workflow({
  id: 'order_shipped',
  reentry: { mode: 'concurrent' },
  trigger: shipped,
}).push(
  push.orderShipped,
  {
    name: u.name,
    orderId: shipped.payload.order_id,
    carrier: shipped.payload.carrier,
  },
  { devices: 'latest' } // leave out to reach every device
);

Recipient. The devices the engine keeps in its device table. Your backend registers each token with JourneyClient.registerDevice (POST /devices), and a token moves to the latest user that registers it:

ts
// your api, when the app reports its token
import { JourneyClient } from 'sendwend/client';
import { contract } from './contract';

const journeys = new JourneyClient({
  contract,
  origin: WORKFLOW_ORIGIN,
  token: WORKFLOW_API_TOKEN,
});

await journeys.registerDevice({ deviceId, userId, token, platform: 'ios' }); // 'ios' | 'android' | 'web'

platform picks the provider: ios goes to APNs, android to FCM, web to the browser's push service. A user with no device is skipped: no copy, no row, and the log says push order_shipped_push skipped: no device for user u_123. A topic push the user opted out of on push (the topic, or all push) is skipped too. Branch on reachable('push') to do something else for them. Sending events covers sign-out (unbindDevice) and visitors.

What you see. With logMessages, one line per device, the recipient being the device token:

text
[journey] push order_shipped_push → 80f1c3… {"name":"Ada","orderId":"o_1042","carrier":"DHL"}

Each device's copy is its own message row and its own durable step, so one device's refusal does not stop the others. With reporting on, the push carries message_id, and, with WORKFLOW_ORIGIN, delivered_url and opened_url for a client that reports straight to the host. The app reports a tap with JourneyClient.messageOpened(userId, messageId). Studio previews each push template as an iPhone and a Pixel lock screen.

Pitfalls.

  • A token the provider reports as gone is removed. Any other refusal about one device keeps the device and settles the copy under the provider's reason; if one reason shows up for every device, the deployment's configuration is wrong, not the devices.
  • Opt-outs are per channel: a topic switched off for push is still sent by email.
  • FCM does not de-duplicate; APNs and Web Push collapse a repeated copy on the device. See Delivery.

APNs

iOS pushes go straight to Apple with a token-based auth key; there is no Firebase in between, so the app registers its APNs device token with platform: 'ios'.

WhatWhere
apns.topicThe app's bundle id (APNs's apns-topic)
apns.keyId, apns.teamIdThe auth key's 10-character id and the Apple Developer team id
apns.environmentOptional map from mode to sandbox or production
APNS_PRIVATE_KEY_BASE64The .p8 file, base64-encoded
bash
base64 < AuthKey_ABC123DEFG.p8 | tr -d '\n'   # the value of APNS_PRIVATE_KEY_BASE64
wrangler secret put APNS_PRIVATE_KEY_BASE64
ts
apns: {
  topic: 'com.acme.app',
  keyId: 'ABC123DEFG',
  teamId: 'TEAM123456',
  // Unlisted modes: production in production, sandbox otherwise
  environment: { development: 'sandbox', staging: 'production' },
},

The request carries aps.alert with the title and body, sound: 'default', and next to aps the template id, the idempotency key, image and url when the content has them, and the tracking fields (message_id, delivered_url, opened_url). A push with an image or a delivered_url is sent with mutable-content: 1, so a notification service extension can attach the image and report the delivery.

APNs speaks HTTP/2 only. A deployed Worker's fetch negotiates it, and the Node and Lambda hosts use the package's own HTTP/2 client, but wrangler dev cannot. Locally, run the relay from sendwend/apns-relay next to it:

js
// scripts/apns-relay.mjs (Node, development only)
import { startApnsRelay } from 'sendwend/apns-relay';

const relay = await startApnsRelay({ port: 8280 });
// wrangler dev --var APNS_RELAY_ORIGIN:http://localhost:8280

The relay listens on loopback, has no auth of its own and forwards only to Apple's two hosts. It sees the provider JWT, so a production host (ENVIRONMENT unset or production) ignores APNS_RELAY_ORIGIN, calls Apple directly and logs one error saying so.

APNs pitfalls:

  • A development build's token (Xcode, the simulator) is a sandbox token; App Store and TestFlight builds are production. A token sent to the other environment answers BadDeviceToken, and the device is kept.
  • DeviceTokenNotForTopic is a token of another bundle id, such as a development build registered against this backend.
  • BadTopic, TopicDisallowed or a bad provider token are the configuration: every copy settles under that reason until it is fixed.

FCM

Android pushes go through the FCM HTTP v1 API with a service account. Create a key for the Firebase project's service account and store the JSON file base64-encoded:

bash
base64 < service-account.json | tr -d '\n'   # the value of GOOGLE_APPLICATION_CREDENTIALS_BASE64
wrangler secret put GOOGLE_APPLICATION_CREDENTIALS_BASE64
ts
fcm: { androidChannelId: 'journeys' }, // android.notification.channel_id; optional

The app registers its FCM registration token with platform: 'android'. The message carries notification (title, body, image) and data with the template id, the idempotency key, url and the tracking fields, so the app can route a tap and report it. The access token is minted from the service account and reused for its hour, shared by every run of the host.

FCM pitfalls:

  • SENDER_ID_MISMATCH is a token from another Firebase project; INVALID_ARGUMENT keeps the device too. Seen for every device, they mean the service account belongs to the wrong project.
  • THIRD_PARTY_AUTH_ERROR is refused for good; UNREGISTERED and 404 NOT_FOUND remove the token.
  • FCM has no collapse header: a request it never answered settles as no_answer rather than risking a second notification.

Web Push

Browser pushes use standard Web Push with VAPID, one sender for Chrome, Edge, Firefox and Safari. Generate one key pair per environment with generateVapidKeys():

js
// scripts/vapid-keys.mjs
import { generateVapidKeys } from 'sendwend/webpush';

const { publicKey, privateKey } = await generateVapidKeys();
console.log(`VAPID_PUBLIC_KEY=${publicKey}\nVAPID_PRIVATE_KEY=${privateKey}`);

Both keys go in the host's environment (VAPID_PUBLIC_KEY, VAPID_PRIVATE_KEY); the public key also goes to your web app, which subscribes with it. The config's webPush entry takes subject (mailto: or an https: URL), openedEvent (a contract event a notification tap is also recorded as, with { message_id }, so conditions see web opens) and pushServices (extra push service hosts).

The device token is the browser's PushSubscription as JSON. The page subscribes and hands it to your api, which registers it, because the engine's API_TOKEN never reaches the browser:

ts
// web app: after a click, since permission prompts need one
const registration = await navigator.serviceWorker.register('/sw.js');
await navigator.serviceWorker.ready;
if ((await Notification.requestPermission()) === 'granted') {
  const key = VAPID_PUBLIC_KEY.replace(/-/g, '+').replace(/_/g, '/');
  const subscription =
    (await registration.pushManager.getSubscription()) ??
    (await registration.pushManager.subscribe({
      userVisibleOnly: true,
      applicationServerKey: Uint8Array.from(atob(key), (char) =>
        char.charCodeAt(0)
      ),
    }));
  await fetch('/api/push-subscriptions', {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({ token: JSON.stringify(subscription.toJSON()) }),
  });
}
ts
// your api's /api/push-subscriptions handler, for the signed-in user
await journeys.registerDevice({ userId, token, platform: 'web' });

The service worker receives { title, body, image?, url?, template, idempotencyKey, message_id, delivered_url?, opened_url? } as the push event's JSON. Reporting the delivery and the tap straight to the host needs no session: the message id in the URL names the copy.

js
// public/sw.js
const report = (url) =>
  typeof url === 'string'
    ? fetch(url, { method: 'POST', keepalive: true }).catch(() => {})
    : undefined;

self.addEventListener('push', (event) => {
  const message = event.data?.json();
  if (typeof message?.title !== 'string') return;
  event.waitUntil(
    Promise.all([
      self.registration.showNotification(message.title, {
        body: message.body,
        tag: message.idempotencyKey, // a repeated copy replaces the first
        data: message,
      }),
      report(message.delivered_url),
    ])
  );
});

self.addEventListener('notificationclick', (event) => {
  event.notification.close();
  const message = event.notification.data ?? {};
  event.waitUntil(
    Promise.all([
      report(message.opened_url),
      self.clients.openWindow(message.url ?? '/'),
    ])
  );
});

Web Push pitfalls:

  • Only an https endpoint on a browser's push service is accepted (fcm.googleapis.com, *.push.services.mozilla.com, *.notify.windows.com, *.push.apple.com). POST /devices answers 400 for any other; name further hosts in webPush.pushServices.
  • The encrypted payload holds at most 3993 bytes of JSON. A larger one is refused before sending as PayloadTooLarge, so keep title, body and url short.
  • A new VAPID pair invalidates every subscription made with the old one: keep one pair per environment and do not rotate it casually.

Slack

Configure. A Slack incoming webhook URL (a Slack app with incoming webhooks, added to the channel). It is a secret, so it lives in the host's environment, and the template reads it when it sends. Declare it in the environment schema passed to the host, so a missing value fails on the first request with every problem listed:

ts
// src/env.ts
import { minLength, object, type output, string, url } from 'zod/mini';

export const env = object({
  API_TOKEN: string().check(minLength(32)),
  WEBHOOK_SLACK_CS: url(),
  WEBHOOK_DISCORD_COMMUNITY: url(),
});

export type Env = output<typeof env>;
bash
wrangler secret put WEBHOOK_SLACK_CS

Pass it as journeyWorker({ ..., env }) (or journeyLambda's env); on Node, the URL goes in vars.

Template. content returns a Slack incoming-webhook body: text (required, the notification fallback) and optional Block Kit blocks, plus username, icon_emoji and the other fields of SlackContent:

ts
// src/slack/churn-alert.ts
import { slackTemplate } from 'sendwend';
import { optional, strictObject, string } from 'zod/mini';
import type { Env } from '../env';

export default slackTemplate({
  id: 'cs_churn_alert',
  title: 'CS · Churn alert',
  props: strictObject({
    email: optional(string()),
    plan: string(),
    reason: optional(string()),
  }),
  preview: { email: 'john@example.com', plan: 'pro', reason: 'too expensive' },
  webhook: (env: Env) => env.WEBHOOK_SLACK_CS,
  content: ({ email, plan, reason }) => ({
    text: `A ${plan} subscriber canceled`,
    blocks: [
      {
        type: 'section',
        text: {
          type: 'mrkdwn',
          text: `*A ${plan} subscriber canceled*\n${email ?? 'no email on file'} · ${reason ?? 'no reason given'}`,
        },
      },
    ],
  }),
});

Templates import only the Env type: Studio loads them in Node, where the Worker's environment does not exist.

Register.

ts
// src/slack/index.ts
import churnAlert from './churn-alert';

export const slack = { churnAlert };

Send.

ts
// src/workflows/churn-alert.ts
import { trigger, workflow } from 'sendwend';
import { e, u } from '../contract';
import { slack } from '../slack';

const canceled = trigger.event(e.subscription_canceled);

export const churnAlert = workflow({
  id: 'churn_alert',
  reentry: { mode: 'concurrent' },
  trigger: canceled,
}).slack(slack.churnAlert, {
  email: u.email,
  plan: canceled.payload.plan,
  reason: canceled.payload.reason,
});

Recipient. The template's webhook, not a person: Slack posts have no per-user address, no topic and no opt-out. A webhook the environment does not hold settles the copy as not_configured, naming the template.

What you see. [journey] slack cs_churn_alert → u_123 {...} in the development log (there is no recipient address, so the user id is printed), a message row like any other channel, and in Studio the message drawn in Slack's style; a block type the preview does not draw shows as a placeholder naming it.

Pitfalls.

  • A webhook Slack reports as gone (no_service, channel_not_found, channel_is_archived, action_prohibited) or any other 4xx settles the copy undelivered and is not retried, so a deleted webhook drops posts quietly. Watch those reasons.
  • text is required even with blocks; a template that returns none fails the step, because that is the workflow, not the channel.
  • Slack does not de-duplicate a webhook post: one that got no answer settles as no_answer and is not posted again.

Discord

Configure. A Discord channel webhook (the channel's settings, Integrations, Webhooks), stored as a secret exactly like Slack's: WEBHOOK_DISCORD_COMMUNITY in the schema above, then wrangler secret put WEBHOOK_DISCORD_COMMUNITY.

Template. discordTemplate takes the same fields as slackTemplate; content returns a Discord webhook body (content, embeds, username, allowed_mentions, ...). It must show something (content, an embed, a poll or components), and content holds at most 2000 characters:

ts
// src/discord/new-member.ts
import { discordTemplate } from 'sendwend';
import { strictObject, string } from 'zod/mini';
import type { Env } from '../env';

export default discordTemplate({
  id: 'community_new_member',
  title: 'Community · New member',
  props: strictObject({ name: string(), method: string() }),
  preview: { name: 'John Doe', method: 'google' },
  webhook: (env: Env) => env.WEBHOOK_DISCORD_COMMUNITY,
  content: ({ name, method }) => ({
    embeds: [
      {
        title: 'New member',
        description: `${name} just joined (signed up with ${method}).`,
      },
    ],
    allowed_mentions: { parse: [] },
  }),
});

Register and send.

ts
// src/discord/index.ts
import newMember from './new-member';

export const discord = { newMember };
ts
// src/workflows/community-welcome.ts
import { trigger, workflow } from 'sendwend';
import { e, u } from '../contract';
import { discord } from '../discord';

const signedUp = trigger.event(e.sign_up);

export const communityWelcome = workflow({
  id: 'community_welcome',
  reentry: { mode: 'never' },
  trigger: signedUp,
}).discord(discord.newMember, {
  name: u.name,
  method: signedUp.payload.method,
});

Recipient. The template's webhook, as for Slack. What you see: the same log line and message row, and Studio draws the message in Discord's style.

Pitfalls.

  • A 404 or 401 settles as UnknownWebhook (deleted, or its channel is gone); another 4xx as HTTP <status>. Neither is retried.
  • allowed_mentions: { parse: [] } keeps a name like @everyone in user data from pinging the server.
  • Like Slack, a post with no answer is no_answer and not posted again; 429, 408 and 5xx are retried.

Push, else email

.prefer() sends one message on the first channel the user can be reached on, from one push and one email template that declare the same props type. The two tip templates above share tipProps, which is what makes this compile:

ts
// src/workflows/weekly-tip.ts
import { trigger, workflow } from 'sendwend';
import { e, u } from '../contract';
import { email } from '../email';
import { push } from '../push';

export const weeklyTip = workflow({
  id: 'weekly_tip',
  reentry: { mode: 'never' },
  trigger: trigger.event(e.sign_up),
})
  .delay('2 days')
  .prefer(
    [push.weeklyTip, email.weeklyTip],
    { name: u.name },
    { label: 'tip by channel' }
  );

It compiles to the branch you could write by hand, with the same IR and hash:

ts
.branch('tip by channel',
  [reachable('push'), (w) => w.push(push.weeklyTip, { name: u.name })],
  (w) => w.email(email.weeklyTip, { name: u.name }))

Recipient. reachable('push') is true when the user has a device and has not opted out of all push. Then every device gets the push; otherwise the profile's email gets the email, by the rules of each channel above. The choice is made once, when the step is reached.

What you see. One log line and one message row (per device for push) on the channel that was chosen; the canvas shows the branch with its label.

Pitfalls.

  • A topic opt-out on push leaves reachable('push') true. A user who turned off only "tips" on push takes the push arm, the push is skipped as opted out, and no email is sent. Write the branch yourself if that user should get the email.
  • A push that fails retries as a push; it never falls through to email. Devices that refuse settle undelivered, and the journey goes on without an email.
  • Different props, or other channels, need the explicit .branch(). See .prefer().

Other channels

The IR's channel set also has sms, in_app and survey, and the chain has .sms(), .inApp() and .survey() steps. What the SDK ships for them today:

StepIR channelRecipient the engine resolvesTemplate definitionBuilt-in sender
.sms()smsthe profile's phonenone: template.sms<P>(key), by keynone
.inApp()in_appnonenone: template.inApp<P>(key)none
.survey()surveythe profile's emailnone: template.survey<P>(key)none

These steps compile, and their props are typed by the hand-written P, but the config's channels deliver only email, push, Slack and Discord. A copy on one of these channels reaches no sender: it settles undelivered as not_configured and the journey goes on. The host's messages option takes a MessageSender that receives every outbound copy, but it replaces every channel, email included, so it suits a gateway that delivers everything.

To add one channel and keep the built-in ones, use a custom action. Here is an SMS sent when an order ships, with a placeholder provider URL:

ts
// src/actions.ts
import { action } from 'sendwend';
import { PermanentError } from 'sendwend/engine';

// `phone` is optional because the profile field is: the workflow's filter keeps it present
export const sendShippingSms = action<{ phone?: string; orderId: string }>(
  'send_shipping_sms',
  async ({ phone, orderId }, ctx) => {
    if (phone === undefined) return;
    const response = await fetch('https://api.sms-provider.example/messages', {
      method: 'POST',
      headers: {
        authorization: `Bearer ${process.env.SMS_API_KEY}`,
        'content-type': 'application/json',
        // Stable across retries of this node: the provider drops the duplicate
        'idempotency-key': ctx.idempotencyKey,
      },
      body: JSON.stringify({
        to: phone,
        text: `Order ${orderId} has shipped.`,
      }),
    });
    if (response.ok) return;
    // A 4xx will not change on retry; anything else throws and the step retries
    if (
      response.status >= 400 &&
      response.status < 500 &&
      response.status !== 429
    ) {
      throw new PermanentError(`SMS refused: ${response.status}`);
    }
    throw new Error(`SMS provider: ${response.status}`);
  }
);
ts
// src/workflows/order-shipped-sms.ts
import { exists, trigger, workflow } from 'sendwend';
import { sendShippingSms } from '../actions';
import { e, u } from '../contract';

const shipped = trigger.event(e.order_shipped);

export const orderShippedSms = workflow({
  id: 'order_shipped_sms',
  reentry: { mode: 'concurrent' },
  trigger: shipped,
})
  .filter(exists(u.phone), { reason: 'no phone number' })
  .run(sendShippingSms, { phone: u.phone, orderId: shipped.payload.order_id });

The action is registered in the config's actions (as in the config at the top), and compileBundle checks that the action a workflow runs is the object listed there. The handler's context holds only userId and idempotencyKey, not the host's environment, so it reads the provider key the way the runtime exposes secrets to modules: process.env on Node and Lambda, and on a Worker, Cloudflare's import { env } from 'cloudflare:workers'.

An action is not a message, which is the trade-off:

  • It runs at least once: retried when it throws, checkpointed when it succeeds, so it can run twice for one journey. Pass ctx.idempotencyKey to the provider (Delivery).
  • There is no opt-out check, no message row and no delivery report for it. Gate it in the workflow (the filter above), and keep your own record if you need one.
  • A PermanentError stops the retries but still fails the step, and a step that fails without a retry fails the journey. Return instead of throwing if the journey should go on after a refusal.