Basic usage

Basic usage

The everyday loop with Sendwend, carried through one trial-to-paid journey, from a contract field to a deployed workflow receiving events.

Once the project is installed, most changes follow the same loop: declare the data in the contract, describe the audience, write the journey, register it, look at it in Studio, run it in fast-forward, plan the change against production, deploy, and send the events. This page walks the loop once with a trial-to-paid journey for a sample SaaS called Acme.

The journey, in words: when a trial starts, send a welcome. Wait up to two days for a first project, and nudge if none appears. Five days later, send teams an upgrade pitch and everyone else a trial-ending reminder. A subscription ends the journey as a conversion at any point; leaving the trial any other way ends it without one.

Declare the event and the profile field

Every event a journey reacts to and every profile field it reads is declared in the contract. Add the trial's events and a plan field:

ts
// src/contract.ts
import { defineContract, templatesFor } from 'sendwend';
import * as z from 'zod/mini';

export const contract = defineContract({
  events: {
    trial_started: z.looseObject({ source: z.string() }),
    project_created: z.looseObject({ project_id: z.string() }),
    teammate_invited: z.looseObject({}),
    subscription_started: z.looseObject({
      price_id: z.string(),
      value: z.number(),
    }),
  },
  profile: z.strictObject({
    email: z.optional(z.email()),
    name: z.string(),
    plan: z.enum(['trial', 'free', 'pro']),
  }),
  subscriptions: { topics: ['onboarding'] },
});

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

plan is an enum, so eq(u.plan, 'pro ') does not compile. email is optional because not every sign-in gives one: u.email is then typed string | undefined, and the trigger below filters on it.

Write the segments

A segment is a named condition. It can be used in a branch, a wait, a goal or a trigger filter, and Studio lists it with its size.

ts
// src/segments.ts
import { eq, performed, segment } from 'sendwend';
import { e, u } from './contract';

export const onTrial = segment({
  id: 'on_trial',
  condition: eq(u.plan, 'trial'),
});

export const collaborating = segment({
  id: 'collaborating',
  condition: performed(e.teammate_invited),
});

Add the templates

Each email is an emailTemplate with a stable id, a strict props schema, and either a topic the user can opt out of or transactional: true. See Templates and channels.

tsx
// src/email/trial-ending.tsx
import { Button, Html, Text } from '@react-email/components';
import * as z from 'zod/mini';
import { emailTemplate } from '../contract';

export default emailTemplate({
  id: 'trial_ending',
  topic: 'onboarding',
  from: { email: 'hello@acme.test', name: 'Acme' },
  title: 'Trial ending',
  props: z.strictObject({ name: z.string() }),
  subject: 'Your Acme trial ends soon',
  preview: { name: 'Ada' },
  component: ({ name }) => (
    <Html>
      <Text>
        {name}, your trial ends in a few days. Keep your projects by choosing a
        plan.
      </Text>
      <Button href="https://acme.test/billing">Choose a plan</Button>
    </Html>
  ),
});

welcome, first_project and team_upgrade are written the same way. Register them once:

ts
// src/email/index.ts
import firstProject from './first-project';
import teamUpgrade from './team-upgrade';
import trialEnding from './trial-ending';
import welcome from './welcome';

export const email = { welcome, firstProject, teamUpgrade, trialEnding };

Write the workflow

ts
// src/workflows/trial-to-paid.ts
import { exists, not, performed, trigger, workflow } from 'sendwend';
import { e, u } from '../contract';
import { email } from '../email';
import { collaborating, onTrial } from '../segments';

export const trialToPaid = workflow({
  id: 'trial_to_paid',
  description: 'From trial start to a first project, then to a paid plan',
  reentry: { mode: 'never' },
  trigger: trigger.event(e.trial_started, { filter: exists(u.email) }),
  goal: { condition: performed(e.subscription_started), within: '30 days' },
  exitWhen: not(onTrial),
})
  .email(email.welcome, { name: u.name })
  .waitUntil(performed(e.project_created), {
    timeout: '2 days',
    onTimeout: (w) => w.email(email.firstProject, { name: u.name }),
  })
  .delay('5 days')
  .branch(
    'by team',
    [collaborating, (w) => w.email(email.teamUpgrade, { name: u.name })],
    (w) => w.email(email.trialEnding, { name: u.name })
  );

Each piece, and where it is explained in full:

  • Trigger. trigger.event() with a profile filter: a user with no address does not enter at all, so nothing is counted against them. Workflows.
  • Re-entry. Required. never enters each user once, which suits a trial. Re-entry.
  • Goal. Checked at entry and after every step where time passes (delay, timeWindow, waitUntil). A performed() in a goal counts from entry, so a purchase before the trial cannot satisfy it. A match exits and counts as a conversion within 30 days.
  • exitWhen. Leaves without counting as a conversion: here, a user whose plan changed to free.
  • waitUntil. Continues as soon as a project is created. After two days it runs onTimeout and then continues on the main line. A performed() inside it counts from when the wait began. Steps.
  • branch. First match wins; the bare sub-flow in last position is the default arm. The label names the node on the canvas.

The chain is not executed here. It builds a graph that the compiler turns into IR, so the callbacks run once, when the module loads, and u.name is a reference resolved at send time.

Register it in the config

ts
// workflow.config.ts
import { defineConfig } from 'sendwend';
import { contract } from './src/contract';
import { collaborating, onTrial } from './src/segments';
import { templates } from './src/templates';
import { trialToPaid } from './src/workflows/trial-to-paid';

export default defineConfig({
  contract,
  workflows: [trialToPaid],
  segments: [onTrial, collaborating],
  templates,
  email: { unsubscribeUrl: 'https://acme.test/unsubscribe' },
  runtime: { development: { timeScale: 1440, logMessages: true } },
});

Segments a workflow references must be listed in segments, or the compile fails. That check, and the rest, run whenever the config is compiled:

ts
import { compileConfig } from 'sendwend';
import config from './workflow.config';

const bundle = compileConfig(config); // throws ConfigCompileError naming the workflow and node

An unregistered template, a prop the template does not declare, a literal its schema refuses, or a u.xxx the contract does not declare all fail here. Most fail earlier, in the editor.

See it in Studio

bash
pnpm exec sendwend dev

Studio compiles the same config and serves it at http://localhost:4321. The Workflows view draws trial_to_paid as a canvas from the IR; each message card links to its template, and the inspector shows a node's parameters and the line that built it. The Templates view renders every email from its preview props, validated against its schema as a send would be. Edit a file and the canvas refreshes over HMR. Studio is read-only: changes happen in your editor.

Run it in development

Start the Worker with ENVIRONMENT=development (in .dev.vars) and a local Postgres, as in Installation:

bash
npx wrangler dev

At timeScale: 1440, one day of journey time is one minute: the two-day wait times out after two minutes, the five-day delay takes five, and the 30-day goal window closes after half an hour. Start a trial:

ts
import { JourneyClient } from 'sendwend/client';
import { contract } from './src/contract';

const journeys = new JourneyClient({
  contract,
  origin: 'http://localhost:8787',
});

await journeys.ingest({
  userId: 'u_ada',
  profile: { email: 'ada@acme.test', name: 'Ada', plan: 'trial' },
  events: [
    {
      event: 'trial_started',
      payload: { source: 'pricing_page' },
      id: 'trial-u_ada',
    },
  ],
});

logMessages prints the welcome as it is sent. Leave the user alone and the first-project nudge follows two minutes later. Run it again with a new userId and send project_created in between, and the nudge does not go out. Send subscription_started and the goal, checked again when the wait ends, ends the journey as a conversion instead of sending the next email.

Development runs open, so no token is needed. To test the logic without a host at all, see Testing.

Plan the change

Before deploying, compare the new bundle with what is running in production:

bash
pnpm exec sendwend plan --database-url "$DATABASE_URL"

plan compiles the project, reads which workflow versions journeys are still running on, and checks the bundle, with the templates this code would serve, against them: a segment or action a pinned journey names that the bundle drops, a template removed or moved to another channel, a new required prop the pinned props never supplied. It prints the pinned versions, any missing migrations and what would break, and exits non-zero on a problem. Run it in CI ahead of the deploy.

The same diff is available in code. plan() reports each workflow, segment, template and action as added, removed, changed, metadata_only or unchanged:

ts
import { compileConfig, plan } from 'sendwend';
import config from './workflow.config';

const deployed = await fetch('https://workflow.acme.test/bundle', {
  headers: { authorization: `Bearer ${process.env.WORKFLOW_API_TOKEN}` },
}).then((response) => response.json());

const changes = plan(compileConfig(config), deployed);
if (changes.hasChanges)
  console.log(changes.workflows.filter((w) => w.status !== 'unchanged'));

Rewording description is metadata_only: it is outside the content hash, so it is not a new version. Changing '5 days' to '4 days' is changed: journeys already running keep the version they entered on, and new entries get the new delay. See Versioning.

Deploy

bash
npx wrangler deploy

With the version_metadata binding, the new version makes its own bundle live on its first request or cron run, and only over an older one. The host checks the bundle against running journeys again and leaves the routes alone if it would break one. After a wrangler rollback, call POST /bundle/deploy to re-apply the running version's bundle. See Cloudflare.

Send events from your app

JourneyClient is the producer side: plain fetch, no dependencies, typed by the contract. There is no separate track or identify call. ingest carries a profile patch (what an identify would) and events (what a track would) in one batch, merged in that order, so the journey an event starts always finds the address it sends to.

ts
// your API
import { contract } from '@acme/journey-contract';
import { JourneyClient } from 'sendwend/client';

export const journeys = new JourneyClient({
  contract,
  origin: 'https://workflow.acme.test',
  token: process.env.WORKFLOW_API_TOKEN,
});

// sign-up: identify and track together
await journeys.ingest({
  userId: user.id,
  profile: { email: user.email, name: user.name, plan: 'trial' },
  events: [
    { event: 'trial_started', payload: { source }, id: `trial-${user.id}` },
  ],
});

// an event on its own
await journeys.ingest({
  userId: user.id,
  events: [
    {
      event: 'project_created',
      payload: { project_id: project.id },
      id: project.id,
    },
  ],
});

// a profile change on its own: leaving the trial for the free plan triggers exitWhen
await journeys.ingest({ userId: user.id, profile: { plan: 'free' } });

// the conversion
await journeys.ingest({
  userId: user.id,
  profile: { plan: 'pro' },
  events: [
    {
      event: 'subscription_started',
      payload: { price_id: price.id, value: 29 },
      id: `subscription-${subscription.id}`,
    },
  ],
});

A payload or profile value the contract refuses throws JourneyValidationError before any request is made; a failed request throws JourneyClientError with its status and body. Give every event an id you can reproduce from your own data: a retried request then records the event once, and count- and window-based conditions stay correct. See Sending events for visitors, push devices, subscriptions and the queue-backed JourneyQueue.

Where to go next

  • Steps: every step, including .prefer(), .timeWindow(), .cohort() and .run().
  • Delivery: what happens when a send fails, and why a copy is delivered at most once.
  • Monorepo: sharing the contract between your API and the Worker.