Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions .github/scripts/packed-consumer.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,41 @@ try {
JSON.parse(readFileSync(join(fixture, 'node_modules/void/package.json'), 'utf8')).version,
version,
);
if (framework === 'react') {
// A standalone Workflow can be the only Void import in a worker project.
writeFileSync(
join(fixture, 'workflow.mts'),
`import { defineWorkflow } from 'void/workflows';
const job = defineWorkflow<{ id: string }>({
async run(event, step) { return step.do('id', async () => event.payload.id); },
});
declare const receiver: Workflow<{ id: string; recipient: string }>;
// @ts-expect-error The receiver also requires a recipient.
void job.create(receiver, { params: { id: '1' } });
export default job;`,
);
writeFileSync(
join(fixture, 'tsconfig.workflow.json'),
JSON.stringify({
compilerOptions: {
module: 'NodeNext',
target: 'ES2022',
lib: ['ES2022'],
types: [],
strict: true,
noEmit: true,
},
files: ['workflow.mts'],
}),
);
await run(
process.execPath,
[join(fixture, 'node_modules/typescript/bin/tsc'), '-p', 'tsconfig.workflow.json'],
fixture,
);
rmSync(join(fixture, 'workflow.mts'));
rmSync(join(fixture, 'tsconfig.workflow.json'));
}
await run(process.execPath, [cli, 'prepare'], fixture);
await run(manager, manager === 'npm' ? ['ci'] : ['install', '--frozen-lockfile'], fixture);
const vite = join(
Expand Down
2 changes: 2 additions & 0 deletions docs/.vitepress/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ const referenceItems: Array<SidebarItem> = [
{ text: 'Authentication', link: '/reference/api/auth' },
{ text: 'Fetch Client', link: '/reference/api/client' },
{ text: 'Durable State and WebSockets', link: '/reference/api/durable' },
{ text: 'Workflows', link: '/reference/api/workflows' },
{ text: 'Deployment artifacts', link: '/reference/api/deploy' },
{ text: 'Database and Seeding', link: '/reference/api/database' },
{ text: 'Resource Clients', link: '/reference/api/resources' },
Expand Down Expand Up @@ -373,6 +374,7 @@ export default extendConfig(
{ text: 'Sandboxes', link: '/guide/sandboxes' },
{ text: 'Cron Jobs', link: '/guide/jobs' },
{ text: 'Queues', link: '/guide/queues' },
{ text: 'Workflows', link: '/guide/workflows' },
{ text: 'WebSockets', link: '/guide/websockets' },
{ text: 'Server-Sent Events', link: '/guide/sse' },
{ text: 'Live Event Streams', link: '/guide/live' },
Expand Down
170 changes: 170 additions & 0 deletions docs/guide/workflows.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
---
description: 'Run durable multi-step jobs with Cloudflare Workflows: retried steps, sleeps, and typed params.'
outline: deep
---

# Workflows

Use a Workflow for work that runs across several steps and must finish even if one fails, such as onboarding emails, imports, or payment follow-ups. Each step's result is saved, failed steps are retried, and a Workflow can sleep for minutes or days between steps.

Create a module in `workflows/` with `defineWorkflow()`. Void creates the Cloudflare Workflow and its binding for you. Workflows run in local development and in direct Cloudflare deployments (`void deploy --platform cloudflare`).

## Define a workflow

```ts
// workflows/onboarding.ts
import { defineWorkflow } from 'void/workflows';
import type { WorkflowEvent } from 'void/workflows';

export const Onboarding = defineWorkflow({
async run(event: WorkflowEvent<{ userId: string }>, step) {
await step.do('send welcome email', async () => {
await sendWelcomeEmail(event.payload.userId);
});
await step.sleep('wait a day', '1 day');
await step.do('send tips', async () => {
await sendTips(event.payload.userId);
});
},
});

export default Onboarding;
```

Default-export the object returned by `defineWorkflow()`. Named-export it too so routes can import it.

Keep `workflows/` at the project root, including when `sourceDir` is set. Write Workflow definitions as TypeScript or JavaScript ES modules with an import from `void/workflows` and a default export. In CommonJS projects, use `.mjs` or `.mts` for definitions. Subdirectories are supported. Files and directories starting with `_` are excluded from Workflow discovery. If you maintain an explicit `include` list in `tsconfig.json`, add `workflows` so TypeScript checks definitions started outside your app.

`run` receives:

- `event`, with the `payload` passed to `create()`, the `instanceId`, and a `timestamp`
- `step`, Cloudflare's [`WorkflowStep`](https://developers.cloudflare.com/workflows/build/workers-api/#workflowstep) with `step.do()`, `step.sleep()`, `step.sleepUntil()`, and `step.waitForEvent()`
- a context with the Worker `env`

Imports such as `void/env`, `void/db`, and `void/kv` work inside steps. Keep side effects inside `step.do()` so a retry or a resumed instance doesn't repeat them.

Each step attempt has its own D1 session. To start from a bookmark, call `setSession({ bookmark })` inside the step before its first query.

## Start an instance from a route

```ts
// routes/api/signup.ts
import { defineHandler } from 'void';
import { Onboarding } from '../../workflows/onboarding';

export const POST = defineHandler(async () => {
const instance = await Onboarding.create({ params: { userId: 'user_123' } });
return { instanceId: instance.id };
});
```

`create()` accepts the same options as Cloudflare's [`Workflow.create()`](https://developers.cloudflare.com/workflows/build/workers-api/#create), such as `id` and `retention`. Use `createBatch()` to start up to 100 instances at once. Both methods require `params` when your definition requires a payload. If you omit optional params, Cloudflare delivers an empty object as `event.payload`. A schema can supply a different default.

Check on an instance with `get()`:

```ts
// routes/api/onboarding/[id].ts
import { defineHandler } from 'void';
import { Onboarding } from '../../../workflows/onboarding';

export const GET = defineHandler(async (c) => {
const instance = await Onboarding.get(c.req.param('id'));
return instance.status();
});
```

The returned instance can also `pause()`, `resume()`, `restart()`, `terminate()`, and `sendEvent()`.

## Validate params

Pass a [Standard Schema](https://standardschema.dev) validator, such as Zod, Valibot, or ArkType, as `params`. `create()` and `createBatch()` validate the params before starting an instance, and `run` receives the parsed value:

```ts
import * as v from 'valibot';
// workflows/import.ts
import { defineWorkflow } from 'void/workflows';

export const Import = defineWorkflow({
params: v.object({ fileKey: v.string(), notify: v.optional(v.boolean(), false) }),
async run(event, step) {
const rows = await step.do('parse', () => parseFile(event.payload.fileKey));
if (event.payload.notify) {
await step.do('notify', () => notifyOwner(rows.length));
}
},
});

export default Import;
```

Invalid params throw a `WorkflowParamsError`. Its `issues` list each message and path.

## Native Workflow classes

Use `defineWorkflowEntrypoint()` to keep a class that extends Cloudflare's `WorkflowEntrypoint`. Void reads the params type from the class’s `run` method:

```ts
// workflows/report.ts
import { WorkflowEntrypoint } from 'cloudflare:workers';
import type { WorkflowEvent, WorkflowStep } from 'cloudflare:workers';
import { defineWorkflowEntrypoint } from 'void/workflows';

class ReportWorkflow extends WorkflowEntrypoint<unknown, { month: string }> {
async run(event: WorkflowEvent<{ month: string }>, step: WorkflowStep) {
return step.do('build report', () => buildReport(event.payload.month));
}
}

export const Report = defineWorkflowEntrypoint({ class: ReportWorkflow });
export default Report;
```

`Report.create()`, `Report.createBatch()`, and `Report.get()` work as they do for `defineWorkflow()`.

## Names and bindings

Void derives the names from the file's path in `workflows/`, joining directories with `-` as it does for [queues](./queues.md#defining-queues). `workflows/send-welcome.ts` creates:

- the `WORKFLOW_SEND_WELCOME` binding
- the exported `SendWelcomeWorkflow` class
- a Cloudflare Workflow named `<worker-name>_send-welcome`, since Workflow names must be unique within your Cloudflare account

`workflows/order/notifications.ts` creates `WORKFLOW_ORDER_NOTIFICATIONS`, `OrderNotificationsWorkflow`, and `<worker-name>_order-notifications`. A path that starts with a digit, such as `2026-report.ts`, exports the class `Workflow2026Report` and uses the binding `WORKFLOW_2026_REPORT`. Each Workflow must have a unique name.

Instances belong to the Workflow name. Changing the generated Workflow name directs new instances to a different Workflow. To move a file without changing its name, run `void info` first and add the name it suggests:

```ts
export const Onboarding = defineWorkflow({
name: 'onboarding',
async run(event, step) {
// ...
},
});
```

`name` must be a static string containing at least one ASCII letter or digit. To choose the Cloudflare Workflow name yourself, add an entry for the generated binding and class in `void.config.ts`:

```ts
// void.config.ts
import { defineConfig } from 'void/config';

export default defineConfig({
cloudflare: {
workflows: [
{ name: 'onboarding', binding: 'WORKFLOW_ONBOARDING', class_name: 'OnboardingWorkflow' },
],
},
});
```

If the generated Cloudflare Workflow name exceeds 64 characters, use this entry to give it a shorter name.

## Deployment support

Workflows are available on the Workers Free plan, within [Cloudflare's Workflows limits](https://developers.cloudflare.com/workflows/reference/limits/). Deploy to your own Cloudflare account with `void deploy --platform cloudflare`.

If Cloudflare rejects staging because you added, renamed, or removed a Workflow, run `void deploy --platform cloudflare --atomic` for that deployment. The new version receives traffic before Void checks readiness.

To publish the same project's static assets to a connected Void platform, build the app and run `void deploy --platform void --dir dist/client`. You can also set `inference.appType` to `static` or `spa` and run `void deploy --platform void`. If you customize the build output, set `inference.outputDir` to the directory containing your public assets.

Workflows require a native Void app targeting Cloudflare Workers.
2 changes: 1 addition & 1 deletion docs/integrations/cloudflare.md
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@ If readiness or trigger updates fail, Void restores the previous deployment. If

Finish or cancel gradual rollouts in Cloudflare before deploying through Void.

For an existing Durable Object Worker that Cloudflare cannot stage, review the changes and use:
If Cloudflare cannot stage a change to a Durable Object or Workflow class on an existing Worker, review the changes and run the following command.

```sh
void deploy --platform cloudflare --atomic
Expand Down
2 changes: 2 additions & 0 deletions docs/reference/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ Use this reference to find public imports, signatures, and return types. For set
| [Authentication](./api/auth.md) | Sessions, users, and the auth client. |
| [Fetch client](./api/client.md) | Typed requests and errors. |
| [Durable State and WebSockets](./api/durable.md) | Persistent objects and typed connections. |
| [Workflows](./api/workflows.md) | Durable multi-step jobs. |
| [Database and seeding](./api/database.md) | Queries, operators, and seed scripts. |
| [KV, storage, AI, and logging](./api/resources.md) | Resource clients, cache revalidation, and logs. |
| [Deployment artifacts](./api/deploy.md) | Package built apps for managed deployment. |
Expand All @@ -45,6 +46,7 @@ Import Void's app-facing APIs from these paths:
| `void/ws` | `defineRoom`, `defineWebSocket`, `connect`, WebSocket context, connection and action types |
| `void/ws/server` | `getRoom`, `RoomHandle`, `RoomOptions`, `RoomPath`. Server-only: call room actions from routes, auth hooks, queues and cron jobs. |
| `void/durable` | `defineDurableState`, `defineDurableObject`, typed state/RPC/context/migration types |
| `void/workflows` | `defineWorkflow`, `defineWorkflowEntrypoint`, `WorkflowParamsError`, Workflow event/step/API types. Server-only. |
| `void/sse` | `eventStream`, `formatSse`, `formatSseText`, `getLastEventId`, `SseStreamClosedError`, SSE message and stream types |
| `void/sse/client` | `connectEventStream`, browser `EventSource` wrapper types |
| `void/live` | `defineLiveStream`, SSE topic fanout runtime types. Server-only. |
Expand Down
42 changes: 42 additions & 0 deletions docs/reference/api/workflows.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
---
description: 'Durable multi-step Workflows from void/workflows.'
outline: deep
---

# Workflows

Imported from `"void/workflows"`. See [Workflows](../../guide/workflows.md) for the file convention and deployment support.

## `defineWorkflow(definition)` {#defineworkflow-definition}

Defines a Cloudflare Workflow from a run function. The returned object must be the default export of a module under `workflows/`; named-export the same object to start instances elsewhere in the app.

The definition accepts an optional `name`, an optional Standard Schema for `params`, and an async `run(event, step, { env, ctx })` function.

With a schema, `create()` and `createBatch()` accept its input and send its parsed output to Cloudflare. Instances started directly through Cloudflare must supply the payload that `run` expects. Without a schema, the params type comes from the `event` annotation or the type parameter to `defineWorkflow()`.

Pass `params` to `create()` and to every entry in `createBatch()` when the definition requires a payload. Cloudflare delivers an empty object as `event.payload` if params are omitted or the schema returns `undefined`. When your handler accepts optional params, check the fields it needs.

## `defineWorkflowEntrypoint(definition)` {#defineworkflowentrypoint-definition}

Registers a class that extends Cloudflare's `WorkflowEntrypoint`. The params type comes from the class's `run(event)` annotation. You can omit params when the declared payload accepts an empty object.

## `WorkflowApi` {#workflowapi}

| Member | Description |
| ------------------------------ | -------------------------------------------------------------------------------------------------------- |
| `class` | The Workflow entrypoint class for this definition. |
| `create(options?)` | Starts an instance. Options match Cloudflare's `create()`; `params` are typed and validated. |
| `createBatch(instances)` | Starts up to 100 instances and returns Cloudflare's `{ created, errors }` result. |
| `get(id)` | Returns a `WorkflowInstance` for `status()`, `pause()`, `resume()`, `terminate()`, and `sendEvent()`. |
| `create(binding, options?)`, … | Each method accepts an explicit `Workflow` binding for the handler’s payload type as its first argument. |

`name` optionally fixes the resource identity instead of deriving it from the filename. Run `void info` and pin the displayed name before moving a deployed definition.

## `WorkflowParamsError` {#workflowparamserror}

Thrown by `create()` and `createBatch()` when params fail the definition's schema. `issues` is an array of `{ message, path? }`.

## Types {#types}

`WorkflowEvent`, `WorkflowStep`, `WorkflowContext`, `WorkflowCreateOptions`, `WorkflowApi`, and `WorkflowRun`.
Loading