Skip to content
Draft
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
2 changes: 2 additions & 0 deletions docs/.vitepress/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,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 @@ -385,6 +386,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
162 changes: 162 additions & 0 deletions docs/guide/workflows.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
---
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.

TypeScript and JavaScript files are supported. Subdirectories are scanned too, and files or directories starting with `_` are ignored, so keep shared step helpers in files such as `workflows/_email.ts`.

`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.

## 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`. Its `params` are typed from your definition. Use `createBatch()` to start up to 100 instances at once.

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 binds and exports the class without changing it, and reads the params type from its `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`. Each Workflow must have a unique name.

Instances belong to the Workflow name. Renaming the file or the Worker starts a new, empty Workflow, and instances of the old one stop running. 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 words that start with a letter. 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' },
],
},
});
```

## 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`.

Void platforms do not support Workflows yet: `void deploy` to a Void platform stops with an error while `workflows/` contains modules. Workflows are also unavailable in meta-framework apps and on Node.js, Bun, and Deno.
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
57 changes: 57 additions & 0 deletions docs/reference/api/workflows.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
---
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.

```ts
function defineWorkflow<TParams, TEnv>(definition: {
name?: string;
params?: StandardSchemaV1;
run(
event: Readonly<WorkflowEvent<TParams>>,
step: WorkflowStep,
context: { env: TEnv; ctx: ExecutionContext },
): Promise<unknown>;
}): WorkflowApi<WorkflowClass<TParams>, TParams>;
```

With `params`, `run` receives the schema's output type and `create()` accepts its input type. Without it, the params type comes from the `event` annotation.

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

Registers a class that extends Cloudflare's `WorkflowEntrypoint` without changing it. The params type is read from the class's `run(event)` annotation.

```ts
function defineWorkflowEntrypoint<TClass>(definition: {
name?: string;
class: TClass;
}): WorkflowApi<TClass, TParams>;
```

## `WorkflowApi` {#workflowapi}

| Member | Description |
| ------------------------------ | ----------------------------------------------------------------------------------------------------- |
| `class` | The Workflow class Void exports from the Worker. |
| `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 also accepts an explicit `Workflow` binding 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`.
4 changes: 2 additions & 2 deletions docs/reference/cli/setup.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ void info
void info --json
```

Shows each Durable State and WebSocket definition's source file, inferred or explicit name, Worker class, and binding. WebSocket entries also include their route in JSON output. It runs locally without authentication, network requests, or file generation.
Shows each Durable State, WebSocket, and Workflow definition's source file, inferred or explicit name, Worker class, and binding. WebSocket entries also include their route in JSON output. It runs locally without authentication, network requests, or file generation.

Before moving a deployed definition, copy the suggested `name` into `defineDurableState()`, `defineRoom()`, or `defineWebSocket()`. Keep that name after moving the file to preserve the resource. See [Durable State](../../guide/durable-state.md#rename-a-file-while-keeping-its-state) and [WebSockets](../../guide/websockets.md#move-a-route-while-keeping-its-state) for migration flows, including WebSocket parameter renames.
Before moving a deployed definition, copy the suggested `name` into `defineDurableState()`, `defineRoom()`, `defineWebSocket()`, or `defineWorkflow()`. Keep that name after moving the file to preserve the resource. See [Durable State](../../guide/durable-state.md#rename-a-file-while-keeping-its-state) [WebSockets](../../guide/websockets.md#move-a-route-while-keeping-its-state), and [Workflows](../../guide/workflows.md#names-and-bindings) for migration flows, including WebSocket parameter renames.

Resources recorded in `void.lock.json` without a matching definition appear separately. Adopt a suggested name only after identifying the resource you moved. If Void cannot suggest a name, restore its original source and inspect it before moving it again.

Expand Down
4 changes: 4 additions & 0 deletions docs/reference/resource-inference.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ Void automatically detects which Cloudflare resources your project uses by scann
| `QUEUE_*` | `Queue` | `import { queues } from "void/queues"` | `env.QUEUE_*` |
| `VOID_LIVE` | `DurableObjectNamespace` | `import { defineLiveStream } from "void/live"` | n/a |
| filename-derived | `DurableObjectNamespace` | A default-exported `defineDurableState()` module in `durable-objects/` | n/a |
| `WORKFLOW_*` | `Workflow` | A default-exported `defineWorkflow()` or `defineWorkflowEntrypoint()` module in `workflows/` | n/a |

Auth detection also triggers when importing the `auth` specifier from `void/client` or a framework-specific client subpath such as `void/client/react` (but not when importing only `fetch`).

Expand All @@ -29,6 +30,8 @@ use [explicit binding overrides](#explicit-binding-overrides).

Durable state is inferred from files in `durable-objects/`. For example, `durable-objects/shopping-cart.ts` creates the `SHOPPING_CART` binding, exports `ShoppingCartDurableObject`, and records its migration. See [Durable State](../guide/durable-state.md).

Workflows are inferred from files in `workflows/`, including subdirectories; paths with a `_`-prefixed segment are ignored. For example, `workflows/send-welcome.ts` creates the `WORKFLOW_SEND_WELCOME` binding and exports `SendWelcomeWorkflow`. See [Workflows](../guide/workflows.md).

## Scanned Directories

### Standard mode
Expand Down Expand Up @@ -68,6 +71,7 @@ Regardless of mode, these are always checked:
- **SSR entry** such as `src/main.ssr.ts`, for SSR apps that access bindings during rendering
- **Application source** in `src/` or your configured `sourceDir`, including resource and auth imports
- **`durable-objects/`**, which is scanned for typed Durable Object state modules in native Void apps
- **`workflows/`**, which is scanned for Workflow modules and the resources they use in native Void apps

## Custom Scan Directories

Expand Down
Loading