Installation

Installation

Install the SDK, write a contract, a template and a workflow, run them locally against Postgres in fast-forward, and deploy the Worker to Cloudflare.

This page takes a new project from pnpm add sendwend zod to a journey running on your machine, then deployed as a Cloudflare Worker. The files below follow the SDK's examples/cloudflare-demo, trimmed to what this journey uses. For AWS Lambda or a plain Node process, the first five steps are identical; see AWS Lambda and Self-hosting for the host.

A project has four parts: one contract, a set of templates, the workflows, and one workflow.config.ts that registers all of it. The compiler, the Worker and Sendwend Studio all read that one object.

text
my-journeys/
├── src/
│   ├── contract.ts        events, profile fields, topics
│   ├── email/
│   │   ├── index.ts       the email registry
│   │   ├── tip.tsx
│   │   └── welcome.tsx
│   ├── templates.ts       every channel's registry
│   ├── workflows/
│   │   └── welcome.ts
│   └── index.ts           the Worker
├── scripts/db-init.mjs    creates the engine's tables
├── workflow.config.ts
├── wrangler.jsonc
└── .dev.vars              local overrides, not committed

1. Install the packages

bash
pnpm add sendwend zod

The peer dependencies are optional. Install the ones the subpaths you use need:

PeerNeeded by
react, react-domsendwend/react-email, and sendwend/cloudflare, which uses it
postgressendwend/postgres-js
@aws/durable-execution-sdk-js, @aws-sdk/client-lambdasendwend/aws only

For the Cloudflare host in this guide, with emails written in React Email:

bash
pnpm add react react-dom postgres @react-email/components
pnpm add -D wrangler typescript @types/react @sendwend/studio

The Worker's JourneyRunner is typed against a small ambient declaration of cloudflare:workers that ships with the package. Add it to tsconfig.json (the SDK avoids @cloudflare/workers-types because its globals clash with React's DOM types):

json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "lib": ["ES2022", "WebWorker"],
    "jsx": "react-jsx",
    "strict": true,
    "skipLibCheck": true,
    "noEmit": true
  },
  "include": [
    "src",
    "workflow.config.ts",
    "node_modules/sendwend/src/cloudflare/workers.d.ts"
  ]
}

2. Write the contract

The contract declares the events journeys react to and the profile fields they read, as Zod schemas. Put it in a module both your API and the Worker can import. See Contract for the rules.

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

export const contract = defineContract({
  events: {
    sign_up: looseObject({ method: string() }),
    purchase: looseObject({}),
  },
  profile: strictObject({ email: optional(email()), name: string() }),
  subscriptions: { topics: ['tips'] },
});

/** The DSL's reference tables: `e.sign_up`, `u.name`. */
export const e = contract.events;
export const u = contract.user;

/** A template factory whose `topic` is typed by the contract. */
export const { emailTemplate } = templatesFor(contract);

Event payloads are object schemas (looseObject keeps extra analytics fields). The profile is a flat object of string, number, boolean, enum and literal fields. Defaults, transforms and refinements are refused when the contract is defined, because input and output must mean the same JSON.

3. Add templates

Each template is one object with a stable id, a strict props schema, and either transactional: true or a topic the contract declares.

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>
  ),
});
tsx
// src/email/tip.tsx
import { Html, Text } from '@react-email/components';
import { strictObject, string } from 'zod/mini';
import { emailTemplate } from '../contract';

export default emailTemplate({
  id: 'tip',
  topic: 'tips',
  from: { email: 'noreply@acme.test', name: 'Acme' },
  title: 'Tip: templates',
  props: strictObject({ name: string() }),
  subject: 'Start from a template',
  preview: { name: 'John Doe' },
  component: ({ name }) => (
    <Html>
      <Text>
        {name}, most teams start from a template. Pick one and change what you
        need.
      </Text>
    </Html>
  ),
});

Gather them per channel. The workflows send the definitions; the config registers the whole.

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

export const email = { welcome, tip };
ts
// src/templates.ts
import { email } from './email';

export const templates = { email };

See Templates and channels for push, Slack and Discord.

4. Write a workflow

ts
// src/workflows/welcome.ts
import { exists, not, performed, trigger, workflow } from 'sendwend';
import { e, u } from '../contract';
import { email } from '../email';

export const welcomeSeries = workflow({
  id: 'welcome_series',
  reentry: { mode: 'never' },
  name: 'Welcome series',
  trigger: trigger.event(e.sign_up, { filter: exists(u.email) }),
  goal: { condition: performed(e.purchase), within: '7 days' },
})
  .email(email.welcome, { name: u.name })
  .delay('2 days')
  .branch([
    not(performed(e.purchase)),
    (w) => w.email(email.tip, { name: u.name }),
  ]);

id is wire identity: instances, the entry ledger and stats are keyed on it, so rename name instead. reentry is required; see Re-entry.

5. Register it in workflow.config.ts

ts
// workflow.config.ts
import { defineConfig } from 'sendwend';
import { contract } from './src/contract';
import { templates } from './src/templates';
import { welcomeSeries } from './src/workflows/welcome';

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

The ENVIRONMENT variable picks the runtime entry (production when unset). timeScale: 600 turns "1 day" into 2.4 minutes, so the two-day delay above takes 4.8 minutes locally. Time windows are times of day and cannot be compressed, so a scaled journey skips them. A mode with no entry runs in real time without message logs; a production entry, if you write one, only admits timeScale: 1. The unsubscribeUrl is the link the tip email carries, because its topic lets the user opt out; the transactional welcome has none.

Check the project now: pnpm exec sendwend dev serves the canvas and the template previews at http://localhost:4321, or shows the compile error that names the workflow and node.

6. Write the Worker

ts
// src/index.ts
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';

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 }),
});

/** The wrangler `workflows` binding's class_name. */
export const AcmeJourneyRunner = journeys.Runner;

export default { fetch: journeys.fetch, scheduled: journeys.scheduled };

To send through Amazon SES instead, pass sesEmailTransport({ region, credentials }) from sendwend/transports/ses, with credentials from the Worker's env.

json
// wrangler.jsonc
{
  "name": "acme-workflow",
  "main": "src/index.ts",
  "compatibility_date": "2026-09-12",
  "compatibility_flags": ["nodejs_compat"],
  "workflows": [
    {
      "name": "acme-journey",
      "binding": "JOURNEY",
      "class_name": "AcmeJourneyRunner"
    }
  ],
  "hyperdrive": [
    {
      "binding": "HYPERDRIVE",
      "id": "<hyperdrive id>",
      "localConnectionString": "postgres://postgres:pw@localhost:54320/workflow"
    }
  ],
  "version_metadata": { "binding": "CF_VERSION_METADATA" },
  "send_email": [{ "name": "EMAIL" }],
  "vars": {
    "ENVIRONMENT": "production",
    "WORKFLOW_ORIGIN": "https://workflow.acme.test"
  },
  "triggers": { "crons": ["*/15 * * * *"] }
}
EntryWhy
nodejs_compatThe bearer check uses node:crypto's timingSafeEqual
workflowsOne binding runs every journey: the IR is data, so there is one runner class
hyperdriveThe engine's Postgres; localConnectionString is what wrangler dev connects to
version_metadataEach new version makes the bundle compiled into it live by itself
send_emailCloudflare Email, for cloudflareEmailTransport
triggers.cronsThe sweep: clock-only segments, date triggers and upkeep. A 15-minute cron starts a date send within 15 minutes

For local runs, override the mode in .dev.vars (keep it out of git):

bash
# .dev.vars
ENVIRONMENT=development

A host in development runs open, without API_TOKEN, and in fast-forward. Any mode that is not development, test or one with its own runtime entry is held to production's rule: no API_TOKEN, no service.

7. Start a local Postgres

The engine's tables live in one schema, workflow by default. Postgres 15 or later is required (the opt-out table, suppression, uses UNIQUE NULLS NOT DISTINCT).

bash
docker run -d --name workflow-pg -e POSTGRES_PASSWORD=pw -e POSTGRES_DB=workflow -p 54320:5432 postgres:17

Nothing creates tables at runtime. This script, from the demo, creates them with renderPostgresDdl(). Every statement is CREATE ... IF NOT EXISTS, so it is safe to run again:

js
// scripts/db-init.mjs
import { setTimeout as sleep } from 'node:timers/promises';
import postgres from 'postgres';
import { renderPostgresDdl } from 'sendwend/store';

const url =
  process.env.DATABASE_URL ?? 'postgres://postgres:pw@localhost:54320/workflow';
const sql = postgres(url, { max: 1 });
for (let attempt = 1; ; attempt++) {
  try {
    await sql`select 1`;
    break;
  } catch (error) {
    if (attempt === 30) throw error;
    await sleep(1000);
  }
}
await sql.unsafe(renderPostgresDdl());
await sql.end();
console.log(`tables ready at ${url}`);
bash
node scripts/db-init.mjs

If your app already migrates with drizzle, use pnpm exec sendwend generate --out <file> instead: it writes the same tables as one drizzle file for drizzle-kit to migrate. See Postgres.

8. Run it locally

bash
npx wrangler dev

Check that the Worker is up and the journeys are deployed:

bash
curl http://localhost:8787/health
# {"ok":true}
curl -X POST http://localhost:8787/bundle/deploy

With version_metadata, a version applies its own bundle on its first request; POST /bundle/deploy applies it on demand and answers 503 with every missing table or column if the database is not ready.

9. Send the first event

POST /ingest takes the profile and the events it belongs to as one batch: the profile is merged first, so the journey the event starts always finds its recipient.

bash
curl -X POST http://localhost:8787/ingest \
  -H 'content-type: application/json' \
  -d '{
    "userId": "u_1",
    "profile": { "email": "ada@acme.test", "name": "Ada" },
    "events": [{ "event": "sign_up", "payload": { "method": "google" }, "id": "sign_up-u_1" }]
  }'

The id is the occurrence's identity for that user: send the same one twice and it is recorded once. With a contract, a batch that does not match it is refused with a 400 and the field paths, before anything is stored.

10. Check that it works

  • The send. With logMessages: true, the wrangler dev output logs each outbound message with its channel, template, recipient and resolved props. Local Cloudflare Email only simulates: the rendered HTML lands in .wrangler/tmp/email/ and the path is logged.
  • The delay. At timeScale: 600, the tip goes out 4.8 minutes after the welcome. Send a purchase for u_1 before then and the goal ends the journey instead.
  • The preview. GET /preview/welcome?props={"name":"Ada"} renders a template as the Worker would send it.
  • The data. psql postgres://postgres:pw@localhost:54320/workflow and look at the workflow schema: the entry, the instance and the message copy are rows.

11. Deploy to Cloudflare

Create the production database (any Postgres 15+), create its tables, and put Hyperdrive in front of it with query caching off. The engine reads wake subscriptions, profiles and segment membership right after writing them, and a cached answer would miss wakes.

bash
DATABASE_URL='postgres://…' node scripts/db-init.mjs
npx wrangler hyperdrive create acme-workflow --connection-string='postgres://…' --caching-disabled

Put the returned id in wrangler.jsonc, then set the bearer and deploy:

bash
npx wrangler secret put API_TOKEN
pnpm exec sendwend plan --database-url "$DATABASE_URL"
npx wrangler deploy

sendwend plan compiles the project, reads which workflow versions journeys are still running on, and exits non-zero if the new code would break one. Put it in CI ahead of wrangler deploy: on Cloudflare a published version serves at once. The new version then makes its own bundle live on its first request or cron run.

Send events from the service that knows what users do, with JourneyClient:

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

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

await journeys.ingest({
  userId: user.id,
  profile: { email: user.email, name: user.name },
  events: [
    {
      event: 'sign_up',
      payload: { method: 'google' },
      id: `sign_up-${user.id}`,
    },
  ],
});

With a contract, event names and payloads are typed and checked before anything is sent. See Sending events for visitors, devices and the queue, and Cloudflare for the full deployment notes: the email transport, List-Unsubscribe over https, Workflows limits and rollbacks.

Next

Basic usage walks through the everyday loop: a new event, a segment, a journey with a wait and a branch, a plan and a deploy.