Templates and channels

Templates and channels

Typed templates for email, push, Slack and Discord, how they are registered and checked at compile time, and what each channel does before and after a send.

A template is one message: its id, a Zod schema for its props, sample props for previews, and the content (a React email component, a push notification, a Slack or Discord body). Workflows send template definitions, not strings, so the props a step passes are checked against the template's schema in the editor, again when the config compiles, and once more when the message is sent. This page covers how templates are written and registered, and then what each channel does. For a complete, copyable example per channel, from its secrets to what you see once it is sent, see Channel examples.

Writing a template

tsx
// src/email/welcome.tsx
import { Html, Text } from '@react-email/components';
import { strictObject, string } from 'zod/mini';
import { emailTemplate } from '../contract';

export default emailTemplate({
  id: 'welcome',
  transactional: true,
  from: { email: 'noreply@acme.test', name: 'Acme' },
  title: 'Welcome',
  props: strictObject({ name: string() }),
  subject: 'Welcome aboard',
  preview: { name: 'John Doe' },
  component: ({ name }) => (
    <Html>
      <Text>
        Welcome, {name}! Create your first project; it takes a minute.
      </Text>
    </Html>
  ),
});

emailTemplate here comes from templatesFor(contract) in your contract module, so its topic is typed by the contract's topics (see Contract).

Fields every template kind shares:

FieldMeaning
idWire identity, unique per channel. The IR, every send and Studio name the template by it; keep it stable
titleDisplay name in Studio (not the email subject or the notification title)
descriptionOptional, for Studio
propsA strict Zod object schema: the only source of the props type
previewSample props for Studio and previews; parsed against props when the template is declared
redelivery'skip' (default) or 'resend'; see Delivery

The props schema is the single source of truth: the DSL's argument types, the preview and the component's parameter are all derived from it. Rename title to change what people see; renaming id makes it a different template.

Registering templates

Gather templates per channel and register them in the config. Workflows import the same objects they send:

ts
// src/email/index.ts
import tip from './tip';
import welcome from './welcome';

export const email = { welcome, tip };
ts
// workflow.config.ts
export default defineConfig({
  contract,
  workflows: [welcomeSeries],
  templates: { email, push, slack, discord },
  email: { unsubscribeUrl: 'https://acme.test/unsubscribe' },
});

The property names (email.welcome) are JavaScript names only; the template's id is what is stored.

What is checked, and when

WhenCheck
In the editor.email(email.welcome, props) checks props against that template's schema; a push template is not accepted where an email is; a topic the contract does not declare is an error at the topic line
When the module loadsThe props schema is supported, preview parses, from and URLs are valid, topic or transactional is given (not both)
compileConfigAn id registered twice in a channel; a workflow sending a template that is not registered, or a different definition registered under the same id; a missing or undeclared prop; a literal the schema refuses; a prop reading a u.xxx the profile does not declare
Each sendThe resolved props are parsed by the schema before the message is rendered

A compile failure is a ConfigCompileError naming the workflow and node, for example:

text
workflow 'welcome' node 0: email 'nudge': required prop 'name' is missing

Topics and transactional messages

Every email and push template says what it is:

  • topic: 'tips': a topic the contract declares, which the user can opt out of on that channel.
  • transactional: true: a receipt, a login code, an invite. Sent whatever the user opted out of, and an email of this kind carries no unsubscribe link.

Leaving both out, or giving both, is a type error and a compile error, and the error says so in words.

Opt-outs are the engine's own record, per topic and channel. A user can opt out of one topic on email, all email, one topic on push, or all push, and each is a separate flag. Your app reads and writes them with JourneyClient.getSubscriptions and setSubscriptions, which is how a preference page is built: the engine holds the truth, the page shows it. all: false masks every topic of that channel whatever its own flag says, and all: true clears only the channel-wide opt-out, so a topic the user turned off on its own stays off.

A send checks the topic the template declares at the time of the send, so the topic a copy is checked against is the one its unsubscribe link names.

Email

tsx
// src/email/tip.tsx
export default emailTemplate({
  id: 'tip',
  topic: 'tips',
  from: { email: 'noreply@acme.test', name: 'Acme' },
  replyTo: { email: 'support@acme.test', name: 'Acme Support' }, // left out: no Reply-To
  title: 'Weekly tip',
  props: strictObject({ name: string() }),
  subject: 'One thing to try this week',
  preview: { name: 'John Doe' },
  component: ({ name }) => <Layout name={name}>…</Layout>,
});

The host renders the component with sendwend/react-email (React's streaming renderer, which waits for react-email's <Tailwind>) and sends it through its email transport. Each template carries its own from; there is no global sender, so share addresses through a module of your own. replyTo is never inherited.

EmailBefore sendingUnsubscribe link, List-Unsubscribe
topicskipped when the user opted out of that topic, or of all emailyes
transactionalalways sentnone, whatever email.unsubscribeUrl says

An email step needs an email on the profile. Without one the copy is settled undelivered as no_recipient.

A topic email's unsubscribe link is the template's unsubscribeUrl, else the config's email.unsubscribeUrl, else none. Its preference link is the config's email.preferencesUrl with the copy's message id added as m. A layout reads both from the render context, never from a constant, so a template's own URL reaches its HTML and each copy's link names that copy:

tsx
import { Link } from '@react-email/components';
import { useEmailContext } from 'sendwend/email-context';

export function Footer() {
  const { unsubscribeUrl, preferencesUrl } = useEmailContext();
  return (
    <>
      {preferencesUrl !== undefined && (
        <Link href={preferencesUrl}>Email preferences</Link>
      )}
      {unsubscribeUrl !== undefined && (
        <Link href={unsubscribeUrl}>Unsubscribe</Link>
      )}
    </>
  );
}

The resolved topic is in the context too, for a line like "you get these because you subscribed to tips".

A topic email carries two ways out, for two readers:

  • The header, for the mail client. With reporting on (a Postgres store and an https WORKFLOW_ORIGIN), List-Unsubscribe names the host's own /t/u/<message> endpoint, with List-Unsubscribe-Post: List-Unsubscribe=One-Click (RFC 8058). Gmail and Yahoo require one-click unsubscribe from bulk senders. The provider's POST unsubscribes from the email's topic at once; the same URL opened in a browser asks first, offering the topic or all email. Without reporting, the header names the template's unsubscribe link, with no one-click claim. Only https URLs are named, so a local http:// origin sends no header.
  • The footer, for the person. preferencesUrl is your app's own page, reached as https://acme.test/settings/email?m=<message id>. The message id is how the page knows the recipient without a login: an unguessable id that only ever reached that mailbox. The page's API calls getSubscriptionsByMessage(m) and setSubscriptionsByMessage(m, patch); an id that names no copy, or a transactional copy, answers 404, which the page shows as an expired link.

preferencesUrl must not share its origin and path with an unsubscribe URL; the config refuses one that does, because the preference link is tracked as an ordinary click.

Email transports

The transport is the host's email option, chosen independently of where workflows run. Rendering and link tracking happen before it, the same for every provider:

TransportImport
cloudflareEmailTransport({ binding }), a Worker's send_emailsendwend/transports/cloudflare-email
cloudflareEmailTransport({ accountId, apiToken }), REST, anywheresendwend/transports/cloudflare-email
sesEmailTransport({ region, credentials? }), SES v2 over fetchsendwend/transports/ses

A host whose workflows send email but that has no email option (and no messages override) fails when it is created, naming those workflows.

Push

ts
export default pushTemplate({
  id: 'onboarding_tip_push',
  topic: 'tips',
  title: 'Onboarding tip (push)',
  props: strictObject({ name: string() }),
  preview: { name: 'John Doe' },
  content: ({ name }) => ({
    title: 'A tip for today',
    body: `Face a window, ${name}.`,
  }),
});

content(props) returns { title, body, image?, url? }: final text, synchronous and pure, checked before sending. url is the page a browser push opens.

A topic push is skipped while the user opted out of that topic on push, or of all push; a transactional push always goes. push.all: false is the in-app "no promotional notifications" switch that App Store Review Guideline 4.5.4 asks for; a topic set to false turns one category off. Opt-outs are per channel: a topic switched off for push is still sent by email.

Pushes go to the devices the engine keeps. The app registers each token with JourneyClient.registerDevice, and a token moves to the latest user that registers it. Each platform is turned on in the config, with its secret in the environment:

PlatformConfigSecretTransport
iosapns: { topic, keyId, teamId, environment? }APNS_PRIVATE_KEY_BASE64 (the .p8)sendwend/apns
androidfcm: { androidChannelId? }GOOGLE_APPLICATION_CREDENTIALS_BASE64sendwend/fcm
webwebPush: { subject, openedEvent?, pushServices? }VAPID_PUBLIC_KEY, VAPID_PRIVATE_KEYsendwend/webpush

A secret is read only when something is sent on that platform.

  • APNs speaks HTTP/2 only. apns.environment maps a mode to sandbox or production; unlisted modes use production in production and sandbox otherwise. wrangler dev cannot make HTTP/2 requests, so locally you run startApnsRelay from sendwend/apns-relay and point APNS_RELAY_ORIGIN at it; production ignores that variable.
  • FCM uses the HTTP v1 API with a service account.
  • Web Push uses VAPID. Generate a key pair once per environment with generateVapidKeys() from sendwend/webpush. Only an https endpoint on a browser's push service is accepted (Chrome's, Firefox's, Edge's and Safari's); webPush.pushServices adds others. webPush.openedEvent names a contract event that a notification tap is also recorded as, so conditions see web opens.

One device's refusal does not end the journey. A token the provider reports as gone is removed. A refusal about one device (a development build's token sent to the production backend is the usual one) settles that copy undelivered under the provider's reason and keeps the device, and the journey goes on to the user's other devices and the next step. The device is kept because the same answers come from every device when the deployment's own environment or key is wrong, and nothing is deleted on a guess: if one reason shows up for every device, it is the configuration. Transient answers (429, 5xx) are retried. Delivery has the full rule.

A push carries its message_id; the app reports a tap with JourneyClient.messageOpened.

Slack and Discord

Team-channel messages go through incoming webhooks. The webhook URL is a secret, so the template reads it from the host's environment when it sends. Pass the environment's Zod schema to the host (journeyWorker({ env })): it is checked on the first request, every problem listed, and the parsed values are what templates see.

ts
import { slackTemplate } from 'sendwend';
import { strictObject, string } from 'zod/mini';
import type { Env } from '../env';

export default slackTemplate({
  id: 'nps_detractor',
  title: 'NPS detractor (support)',
  props: strictObject({ name: string() }),
  preview: { name: 'John Doe' },
  webhook: (env: Env) => env.WEBHOOK_SLACK_SUPPORT,
  content: ({ name }) => ({ text: `${name} gave us a low NPS score` }),
});

discordTemplate takes the same fields; its content returns a Discord webhook body (content, embeds, allowed_mentions, ...). These templates have no topic and no opt-out. A request the channel refuses for good settles the copy as undelivered rather than retrying, so a team-channel post never holds up the messages after it.

Other channels

.sms(), .inApp() and .survey() compile, and take a hand-typed reference by key: template.sms<P>(key) (also template.inApp, template.survey). The built-in channels deliver email, push, Slack and Discord only; supply anything else with the host's messages option, a MessageSender that receives every outbound copy.

Previews

Every template's preview props are parsed when the template is declared, so a preview that does not match the schema fails at load time, not in Studio. Sendwend Studio renders every template with its preview props (see Studio views), and the host serves GET /preview/<id>?props=<JSON>, which renders a template with the subject in the x-subject header. A preview renders the preference link with a placeholder message id, PREVIEW_MESSAGE_ID.

  • Channel examples: one end-to-end example per channel.
  • Steps: the message steps that send these templates.
  • Delivery: what happens when a send fails.
  • Versioning: why a fixed typo reaches journeys already running.