workflow 5.0.0-beta.34 → 5.0.0-beta.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/dist/internal/errors.d.ts +1 -1
  2. package/dist/internal/errors.d.ts.map +1 -1
  3. package/dist/internal/errors.js +2 -2
  4. package/dist/nest-builder.d.ts +2 -0
  5. package/dist/nest-builder.d.ts.map +1 -0
  6. package/dist/nest-builder.js +2 -0
  7. package/dist/nest-vercel-builder.d.ts +2 -0
  8. package/dist/nest-vercel-builder.d.ts.map +1 -0
  9. package/dist/nest-vercel-builder.js +2 -0
  10. package/docs/api-reference/workflow/create-hook.mdx +43 -2
  11. package/docs/api-reference/workflow/define-hook.mdx +26 -24
  12. package/docs/api-reference/workflow/fatal-error.mdx +29 -7
  13. package/docs/api-reference/workflow/fetch.mdx +3 -4
  14. package/docs/api-reference/workflow/sleep.mdx +1 -1
  15. package/docs/api-reference/workflow-api/get-hook-by-token.mdx +2 -0
  16. package/docs/api-reference/workflow-api/resume-hook.mdx +2 -0
  17. package/docs/api-reference/workflow-api/resume-webhook.mdx +6 -4
  18. package/docs/api-reference/workflow-api/start.mdx +1 -1
  19. package/docs/api-reference/workflow-errors/index.mdx +3 -0
  20. package/docs/api-reference/workflow-errors/meta.json +1 -0
  21. package/docs/api-reference/workflow-errors/precondition-failed-error.mdx +62 -0
  22. package/docs/api-reference/workflow-nest/nest-local-builder.mdx +1 -1
  23. package/docs/comparisons/index.mdx +66 -0
  24. package/docs/comparisons/meta.json +11 -0
  25. package/docs/comparisons/workflow-sdk-vs-aws-agentcore.mdx +55 -0
  26. package/docs/comparisons/workflow-sdk-vs-aws-step-functions.mdx +111 -0
  27. package/docs/comparisons/workflow-sdk-vs-cloudflare-workflows.mdx +71 -0
  28. package/docs/comparisons/workflow-sdk-vs-inngest.mdx +102 -0
  29. package/docs/comparisons/workflow-sdk-vs-temporal.mdx +123 -0
  30. package/docs/comparisons/workflow-sdk-vs-trigger-dev.mdx +103 -0
  31. package/docs/configuration/runtime-tuning.mdx +26 -0
  32. package/docs/configuration/worlds.mdx +6 -7
  33. package/docs/cookbook/common-patterns/idempotency.mdx +1 -1
  34. package/docs/{deploying/index.mdx → deploying.mdx} +6 -8
  35. package/docs/foundations/hooks.mdx +1 -1
  36. package/docs/foundations/idempotency.mdx +16 -9
  37. package/docs/getting-started/astro.mdx +1 -1
  38. package/docs/getting-started/express.mdx +1 -1
  39. package/docs/getting-started/fastify.mdx +1 -1
  40. package/docs/getting-started/hono.mdx +1 -1
  41. package/docs/getting-started/index.mdx +10 -3
  42. package/docs/getting-started/meta.json +3 -1
  43. package/docs/getting-started/nestjs.mdx +63 -2
  44. package/docs/getting-started/next.mdx +2 -2
  45. package/docs/getting-started/nitro.mdx +1 -1
  46. package/docs/getting-started/nuxt.mdx +1 -1
  47. package/docs/getting-started/python.mdx +19 -17
  48. package/docs/getting-started/react-router/index.mdx +33 -0
  49. package/docs/getting-started/react-router/meta.json +5 -0
  50. package/docs/getting-started/react-router/v7.mdx +237 -0
  51. package/docs/getting-started/react-router/v8.mdx +232 -0
  52. package/docs/getting-started/sveltekit.mdx +1 -1
  53. package/docs/getting-started/vite.mdx +1 -1
  54. package/docs/how-it-works/encryption.mdx +3 -3
  55. package/docs/how-it-works/event-sourcing.mdx +6 -6
  56. package/docs/how-it-works/framework-integrations.mdx +3 -3
  57. package/docs/meta.json +1 -1
  58. package/docs/observability/attributes.mdx +9 -0
  59. package/package.json +13 -11
  60. package/docs/deploying/building-a-world.mdx +0 -251
  61. package/docs/deploying/meta.json +0 -4
  62. package/docs/deploying/world/local-world.mdx +0 -101
  63. package/docs/deploying/world/meta.json +0 -4
  64. package/docs/deploying/world/postgres-world.mdx +0 -288
  65. package/docs/deploying/world/vercel-world.mdx +0 -275
  66. package/docs/migration-guides/index.mdx +0 -34
  67. package/docs/migration-guides/meta.json +0 -9
  68. package/docs/migration-guides/migrating-from-aws-step-functions.mdx +0 -362
  69. package/docs/migration-guides/migrating-from-inngest.mdx +0 -308
  70. package/docs/migration-guides/migrating-from-temporal.mdx +0 -317
  71. package/docs/migration-guides/migrating-from-trigger-dev.mdx +0 -332
@@ -1,317 +0,0 @@
1
- ---
2
- title: Migrating from Temporal
3
- description: Move a Temporal TypeScript workflow to the Workflow SDK by replacing Activities, Workers, Signals, and Child Workflows with Workflows, Steps, Hooks, and start()/getRun().
4
- type: guide
5
- summary: Translate a Temporal app into the Workflow SDK with side-by-side code examples.
6
- prerequisites:
7
- - /docs/getting-started/next
8
- - /docs/foundations/workflows-and-steps
9
- related:
10
- - /docs/foundations/starting-workflows
11
- - /docs/foundations/errors-and-retries
12
- - /docs/foundations/hooks
13
- - /docs/foundations/streaming
14
- - /docs/deploying/world/vercel-world
15
- ---
16
-
17
- <CopyPrompt
18
- text="Refactor this Temporal TypeScript code to Workflow SDK. Run `npm i workflow`. Replace Temporal workflow functions with exported async functions containing `&quot;use workflow&quot;`. Replace Activities with helper functions containing `&quot;use step&quot;`. Replace timers with `sleep()` from `workflow`. Replace Signals with `defineHook()` plus `resumeHook()` from `workflow/api`, or `createWebhook()` when an HTTP callback URL is needed. Replace Child Workflows with `start(childWorkflow, args)` and coordinate completion with hooks or `getRun()`. Remove Temporal workers; instead expose API routes or server functions that call `start()` and `getRun()` from `workflow/api`. Preserve idempotency and retries with normal errors, `RetryableError`, and `FatalError`, then add a verification path for each migrated workflow."
19
- />
20
-
21
- <Callout type="info">
22
- Install the Workflow SDK migration skill:
23
-
24
- ```bash
25
- npx skills add https://github.com/vercel/workflow --skill migrating-to-workflow-sdk
26
- ```
27
- </Callout>
28
-
29
- ## Why migrate to the Workflow SDK
30
-
31
- - Streaming is built in. Durable progress writes go to named streams via `getWritable({ namespace })`, and clients read them directly. No separate WebSocket, SSE, or progress-polling layer to operate.
32
- - Infrastructure and orchestration live in a single deployment. There is no separate Worker fleet or Temporal Server to run. The runtime, step logic, and orchestration share the app's observability and log aggregation.
33
- - TypeScript-first developer experience. Workflows and steps live in the same file with plain `await` control flow, `try/catch`, and `Promise.all`.
34
- - Agent-first tooling. A first-class CLI (`npx workflow`), [`@workflow/ai` integration for durable AI agents](/docs/ai), and a bundled Claude skill for AI-assisted authoring.
35
- - Per-step retry controls. `RetryableError`, `FatalError`, and `maxRetries` live at the step boundary instead of an Activity-level retry policy configured elsewhere.
36
-
37
- ## What changes when you leave Temporal
38
-
39
- Temporal requires operating a control plane (Temporal Server or Cloud), a Worker fleet, Activity modules wired through `proxyActivities`, and Task Queues. The workflow code is durable; the surrounding infrastructure is substantial.
40
-
41
- The Workflow SDK runs on managed infrastructure. Write `"use workflow"` functions that orchestrate `"use step"` functions in the same file, in plain TypeScript. There are no Workers, Task Queues, or separate Activity modules. Durable replay, automatic retries, and event history are handled by the runtime.
42
-
43
- Workflow functions must still be deterministic — no `Date.now()`, `Math.random()`, direct network I/O, or wall-clock branches inside `"use workflow"`. Move any such logic into a step, as you do today with Activities.
44
-
45
- Migration removes infrastructure and collapses indirection. Business logic stays as regular async TypeScript.
46
-
47
- ## Concept mapping
48
-
49
- | Temporal | Workflow SDK | Migration note |
50
- | --- | --- | --- |
51
- | Workflow Definition / Workflow Execution | `"use workflow"` function / run started with `start()` | Keep orchestration code in the workflow function. |
52
- | Activity | `"use step"` function | Put side effects and Node.js access in steps. |
53
- | Worker + Task Queue | Managed execution | No worker fleet or polling loop to operate. |
54
- | Signal | `createHook()` or `createWebhook()` | Use hooks for typed resume signals; webhooks for HTTP callbacks. |
55
- | Query | `getWritable({ namespace: 'status' })` stream | Durably stream status updates from the workflow. Clients read from the stream instead of polling a database. |
56
- | Update | `createHook()` + `resumeHook()` (one-way) | Temporal Updates return a value to the caller; hooks do not. If the Update returns data, either write the result to a named stream via `getWritable()` and have the caller read from it, or keep an HTTP read route that fetches the workflow's current state. |
57
- | Child Workflow | `start()` plus a `"use step"` wrapper around `getRun()` | Spawn a child run and return the `Run` object so observability can deep-link into child runs. |
58
- | Activity retry policy | Step retries, `RetryableError`, `FatalError`, `maxRetries` | Retries live at the step boundary. |
59
- | Event History | Workflow event log / run timeline | Same durable replay; built-in observability UI replaces Temporal Web. Search attributes and visibility APIs have no direct equivalent — filter by run status and timestamps instead. |
60
-
61
- ## Translate your first workflow
62
-
63
- ### Minimal translation
64
-
65
- Start with the directive change. The Temporal definition proxies activities through a module; the Workflow SDK version puts the directive inline.
66
-
67
- {/* @skip-typecheck: Temporal SDK types not available */}
68
- ```typescript title="workflows/order.ts (Temporal)"
69
- import * as wf from '@temporalio/workflow';
70
- import type * as activities from './activities';
71
-
72
- const { chargePayment } = wf.proxyActivities<typeof activities>({
73
- startToCloseTimeout: '5 minutes',
74
- });
75
-
76
- export async function processOrder(orderId: string) {
77
- await chargePayment(orderId);
78
- return { orderId, status: 'completed' };
79
- }
80
- ```
81
-
82
- ```typescript title="workflows/order.ts (Workflow SDK)"
83
- export async function processOrder(orderId: string) {
84
- 'use workflow'; // [!code highlight]
85
- await chargePayment(orderId);
86
- return { orderId, status: 'completed' };
87
- }
88
- ```
89
-
90
- **What changed:** `proxyActivities` and the activity module disappear. The orchestrator is plain async TypeScript marked with `"use workflow"`.
91
-
92
- ### Adding a step
93
-
94
- Side effects move into a colocated `"use step"` function:
95
-
96
- ```typescript title="workflow/workflows/order.ts"
97
- async function chargePayment(orderId: string) {
98
- 'use step'; // [!code highlight]
99
- await fetch(`https://example.com/api/orders/${orderId}/charge`, {
100
- method: 'POST',
101
- });
102
- }
103
- ```
104
-
105
- Additional steps (`loadOrder`, `reserveInventory`) follow the same shape and can be called from the workflow in sequence.
106
-
107
- ### Starting the run
108
-
109
- Replace Worker + Task Queue wiring with a single `start()` call from an API route:
110
-
111
- ```typescript title="app/api/orders/route.ts"
112
- import { start } from 'workflow/api';
113
- import { processOrder } from '@/workflows/order';
114
-
115
- export async function POST(request: Request) {
116
- const { orderId } = (await request.json()) as { orderId: string };
117
- const run = await start(processOrder, [orderId]); // [!code highlight]
118
- return Response.json({ runId: run.runId });
119
- }
120
- ```
121
-
122
- ## Wait for an external signal
123
-
124
- ### Minimal translation
125
-
126
- Temporal needs a signal definition, a handler, and a `condition()` guard. The Workflow SDK collapses all three into a single `createHook()` + `await`.
127
-
128
- {/* @skip-typecheck: Temporal SDK types not available */}
129
- ```typescript title="temporal/workflows/refund.ts"
130
- export const approveRefund = wf.defineSignal<[boolean]>('approveRefund');
131
-
132
- export async function refundWorkflow(refundId: string) {
133
- let approved: boolean | undefined;
134
- wf.setHandler(approveRefund, (v) => { approved = v; });
135
- await wf.condition(() => approved !== undefined);
136
- return { refundId, approved };
137
- }
138
- ```
139
-
140
- ```typescript title="workflow/workflows/refund.ts"
141
- import { createHook } from 'workflow';
142
-
143
- export async function refundWorkflow(refundId: string) {
144
- 'use workflow';
145
- using approval = createHook<{ approved: boolean }>({
146
- token: `refund:${refundId}:approval`, // [!code highlight]
147
- });
148
- const { approved } = await approval; // [!code highlight]
149
- return { refundId, approved };
150
- }
151
- ```
152
-
153
- The workflow suspends durably at `await approval` until resumed. No polling, no handler registration.
154
-
155
- Requires TypeScript 5.2+ for the `using` keyword. On older TypeScript, assign the hook to a `const` and call `resumeHook()` from the consuming code path.
156
-
157
- ### Resuming from an API route
158
-
159
- Any HTTP caller can resume by token:
160
-
161
- ```typescript title="app/api/refunds/[refundId]/approve/route.ts"
162
- import { resumeHook } from 'workflow/api';
163
-
164
- export async function POST(request: Request, { params }: { params: Promise<{ refundId: string }> }) {
165
- const { refundId } = await params;
166
- const body = (await request.json()) as { approved: boolean };
167
- await resumeHook(`refund:${refundId}:approval`, body); // [!code highlight]
168
- return Response.json({ ok: true });
169
- }
170
- ```
171
-
172
- <Callout type="info">
173
- Temporal Queries expose in-memory workflow state on demand. In the Workflow SDK, the equivalent is a durable stream: call `getWritable({ namespace: 'status' })` from inside the workflow to write status updates, and have clients read from the end of that stream to get the current state. Hooks are the write channel for resuming a paused workflow with new data.
174
- </Callout>
175
-
176
- ## Spawn a child workflow
177
-
178
- ### Minimal translation
179
-
180
- In v5, call `start()` directly from the workflow to spawn a child run. Wrap `getRun()` and `returnValue` access in a `"use step"` function when you need to await the child result. Return the `Run` object (not a plain `runId` string) so workflow observability can deep-link into child runs.
181
-
182
- ```typescript title="workflow/workflows/parent.ts"
183
- import { start } from 'workflow/api';
184
-
185
- export async function parentWorkflow(item: string) {
186
- 'use workflow';
187
- const child = await start(childWorkflow, [item]); // [!code highlight]
188
- return { childRunId: child.runId };
189
- }
190
- ```
191
-
192
- ### Awaiting the child's return value
193
-
194
- A second step fetches the run and awaits `returnValue`:
195
-
196
- ```typescript title="workflow/workflows/parent.ts"
197
- import { getRun } from 'workflow/api';
198
-
199
- async function collectResult(runId: string) {
200
- 'use step';
201
- const run = getRun(runId);
202
- return (await run.returnValue) as { item: string; result: string }; // [!code highlight]
203
- }
204
- ```
205
-
206
- Call `start()` and then `collectResult()` from the parent in sequence: `const result = await collectResult(child.runId)`. To fan out, call `start()` inside a loop, then `Promise.all` the `collectResult` calls.
207
-
208
- <Callout type="warn">
209
- Activity retry policy moves to the step boundary. Use `maxRetries`, `RetryableError`, and `FatalError` on each step instead of a single workflow-wide retry block.
210
-
211
- Temporal's per-activity timeouts (`startToCloseTimeout`, `scheduleToCloseTimeout`, `heartbeatTimeout`) have no direct Workflow SDK equivalent. Enforce per-step deadlines inside the step using `AbortSignal.timeout(ms)` (e.g. on `fetch`), or wrap the call from the workflow in `Promise.race(step(), sleep('5m'))` to bail out after a bounded duration.
212
-
213
- Temporal's retry policy knobs (`initialInterval`, `backoffCoefficient`, `maximumInterval`, `nonRetryableErrorTypes`) don't port 1:1 — only `maxRetries` is configurable at the step boundary. Classify retryability with `RetryableError` (retryable) and `FatalError` (terminal) instead of listing error types, and control the delay between attempts with `new RetryableError(msg, { retryAfter: '5s' })`.
214
-
215
- Set `maxRetries` as a property assignment on the step function:
216
-
217
- ```typescript
218
- async function chargePayment(orderId: string) {
219
- "use step";
220
- // ...
221
- }
222
- chargePayment.maxRetries = 5;
223
- ```
224
-
225
- See [/docs/foundations/errors-and-retries](/docs/foundations/errors-and-retries) for full retry docs.
226
- </Callout>
227
-
228
- ## What you stop operating
229
-
230
- - **Temporal Server or Cloud.** Durable state lives in the managed event log.
231
- - **Worker fleet.** The runtime schedules execution; workflows run where the app runs.
232
- - **Task Queues.** No queue routing to configure or monitor.
233
- - **Activity modules and `proxyActivities`.** Steps live next to the workflow that calls them.
234
- - **Custom progress transport.** `getWritable()` streams updates from steps.
235
-
236
- Suspended workflows (on `sleep()` or a hook) consume no compute until resumed.
237
-
238
- ## Step-by-step first migration
239
-
240
- Pick one Temporal workflow and migrate it end-to-end before touching the rest. The steps below describe the smallest viable path.
241
-
242
- ### Step 1: Install the Workflow SDK
243
-
244
- Add the runtime. The Next.js integration ships as a subpath (`workflow/next`) of the same package.
245
-
246
- ```bash
247
- pnpm add workflow
248
- ```
249
-
250
- ### Step 2: Collapse Activities into step functions
251
-
252
- Delete the `activities/` module and the `proxyActivities` call. Each former Activity becomes a plain async function with `"use step"` on the first line, living next to the orchestrator.
253
-
254
- ```ts title="workflows/order.ts"
255
- async function loadOrder(id: string) {
256
- "use step"; // [!code highlight]
257
- return fetch(`/api/orders/${id}`).then((r) => r.json());
258
- }
259
- ```
260
-
261
- ### Step 3: Mark the orchestrator with `"use workflow"`
262
-
263
- Keep the existing control flow: `await`, `try/catch`, `Promise.all`. The directive turns the function into a durable replay target.
264
-
265
- ```ts
266
- export async function processOrder(orderId: string) {
267
- "use workflow"; // [!code highlight]
268
- const order = await loadOrder(orderId);
269
- // ...
270
- }
271
- ```
272
-
273
- ### Step 4: Replace Signals with hooks
274
-
275
- Swap `defineSignal` + `setHandler` for `createHook()`. Callers `resumeHook(token, payload)` instead of `handle.signal(signalDef, payload)` on a `WorkflowHandle` obtained from `client.workflow.getHandle(workflowId)`.
276
-
277
- ### Step 5: Start runs from an API route or server action
278
-
279
- Delete the Worker bootstrap. Launch runs from an API route or server action with `start()`:
280
-
281
- ```ts title="app/api/orders/route.ts"
282
- import { start } from "workflow/api";
283
- import { processOrder } from "@/workflows/order";
284
-
285
- export async function POST(req: Request) {
286
- const { orderId } = await req.json();
287
- const run = await start(processOrder, [orderId]);
288
- return Response.json({ runId: run.runId });
289
- }
290
- ```
291
-
292
- ### Step 6: Retire the Temporal infrastructure
293
-
294
- Remove the Worker process, `@temporalio/*` dependencies, and the Temporal Server or Cloud connection. Verify the run in the built-in observability UI (`npx workflow web`) before shipping.
295
-
296
- ## Features without a 1:1 equivalent
297
-
298
- - **Search attributes / visibility queries.** Temporal's search attribute system has no direct analog. Filter runs by status and timestamps via `getRun()` / observability UI.
299
- - **Event history archival.** Temporal archives histories to S3/GCS for long-term retention. Workflow SDK event logs are durable, but retention depends on the integration you are using. For example, see [Vercel Workflow Storage Retention](https://vercel.com/docs/workflows/pricing#storage-retention) for Vercel.
300
- - **Per-activity timeouts (`startToCloseTimeout`, `scheduleToCloseTimeout`, `heartbeatTimeout`).** Implement deadlines inside the step with `AbortSignal.timeout(ms)`, or wrap the call in `Promise.race(step(), sleep(...))` from the workflow.
301
- - **Rich retry policy (`initialInterval`, `backoffCoefficient`, `maximumInterval`, `nonRetryableErrorTypes`).** Only `maxRetries` is configurable. Classify retryability with `RetryableError`/`FatalError`; control delay between attempts via `new RetryableError(msg, { retryAfter: '5s' })`.
302
- - **Workers + task queues.** Managed deployments replace workers; self-hosted deployments still need a `World` implementation (see [/docs/deploying/building-a-world](/docs/deploying/building-a-world)).
303
-
304
- ## Quick-start checklist
305
-
306
- - Move orchestration into a `"use workflow"` function.
307
- - Convert each Activity into a `"use step"` function.
308
- - Remove Worker and Task Queue code. Start workflows from the app with `start()`.
309
- - Replace Signals with `createHook()` or `createWebhook()` for HTTP callers.
310
- - Use `start()` directly for child workflows, and wrap `getRun()` in a `"use step"` function when collecting results. Return the `Run` object from `start()` so observability can deep-link into child runs.
311
- - Set retry policy per step with `maxRetries`, `RetryableError`, and `FatalError`.
312
- - Use `getStepMetadata().stepId` as the idempotency key for external side effects.
313
- - Stream status and progress from steps with `getWritable({ namespace: 'status' })`, and have clients read from the stream instead of polling.
314
- - Deploy the app and verify runs end-to-end in the built-in observability UI.
315
-
316
- ---
317
- *Verified against `workflow@5.0.0-beta.1` and `@temporalio/workflow@1.16` on 2026-04-16.*
@@ -1,332 +0,0 @@
1
- ---
2
- title: Migrating from trigger.dev
3
- description: Move a trigger.dev v3 TypeScript app to the Workflow SDK by replacing task(), schemaTask(), wait.for / wait.forToken, triggerAndWait, and metadata streams with Workflows, Steps, Hooks, and start() / getRun().
4
- type: guide
5
- summary: Translate a trigger.dev v3 app into the Workflow SDK with side-by-side code examples.
6
- prerequisites:
7
- - /docs/getting-started/next
8
- - /docs/foundations/workflows-and-steps
9
- related:
10
- - /docs/foundations/starting-workflows
11
- - /docs/foundations/errors-and-retries
12
- - /docs/foundations/hooks
13
- - /docs/foundations/streaming
14
- - /docs/deploying/world/vercel-world
15
- ---
16
-
17
- <CopyPrompt
18
- text="Convert this trigger.dev setup to Workflow SDK. Run `npm i workflow`. Replace each `task()` or job entrypoint with an exported async workflow function containing `&quot;use workflow&quot;`. Replace trigger.dev task bodies that do side effects with `&quot;use step&quot;` helper functions. Replace waits/delays with `sleep()` from `workflow`. Replace external triggers or resume points with `defineHook()`/`resumeHook()` or `createWebhook()`. Replace run creation/status calls with `start()` and `getRun()` from `workflow/api`. Replace metadata/progress streaming with `getWritable()` from `workflow` when the UI needs live updates. Preserve retry semantics with normal errors, `RetryableError`, and `FatalError`, then add a local verification that starts the migrated workflow and checks the expected result or stream."
19
- />
20
-
21
- <Callout type="info">
22
- Install the Workflow SDK migration skill:
23
-
24
- ```bash
25
- npx skills add https://github.com/vercel/workflow --skill migrating-to-workflow-sdk
26
- ```
27
- </Callout>
28
-
29
- ## Why migrate to the Workflow SDK?
30
-
31
- - Streaming is built in via named streams (`getWritable()` and `getWritable({ namespace })`). Durable status writes replace `metadata.stream()` and `metadata.set()`, and clients read from the end of the stream for current status.
32
- - Orchestration and infrastructure live in a single deployment. There is no separate trigger.dev cloud or self-hosted worker fleet to operate.
33
- - TypeScript-first DX: plain async/await control flow, no `task()` factory, no `schemaTask()` wrapper for payloads you already type with TypeScript.
34
- - Agent-first tooling: the `npx workflow` CLI, `@workflow/ai` for durable AI agents, and a Claude skill for generating workflows.
35
- - Retry policy is per step. Throw `RetryableError` to retry with a delay, or `FatalError` to stop. There is no central task-level retry config.
36
-
37
- ## What changes when you leave trigger.dev?
38
-
39
- trigger.dev v3 defines durable work with `task()` or `schemaTask()` from `@trigger.dev/sdk` (trigger.dev v3), deploys tasks to the trigger.dev cloud or a self-hosted instance, and triggers runs via `tasks.trigger()`. A separate worker fleet picks up runs, applies retry policies, and routes `wait.for`, `wait.forToken`, and `metadata.stream` calls through the platform.
40
-
41
- The Workflow SDK replaces that with `"use workflow"` functions that orchestrate `"use step"` functions in plain TypeScript. There is no task registry, separate deploy target, or SDK client. Durable replay, retries, and event history ship with the runtime.
42
-
43
- Migration collapses the task abstraction into plain async functions. Business logic stays the same.
44
-
45
- ## Concept mapping
46
-
47
- | trigger.dev | Workflow SDK | Migration note |
48
- | --- | --- | --- |
49
- | `task({ id, run })` | `"use workflow"` function started with `start()` | No factory or id registry. |
50
- | `schemaTask({ schema, run })` | Typed function + `"use workflow"` | Validate inputs at the call site. |
51
- | Inline `run` body | `"use step"` function | Side effects move into named steps. |
52
- | `logger` / `metadata.set` | `console` + `getWritable({ namespace: 'status' })` | Logs flow through the run timeline. Status writes go on a named stream. |
53
- | `wait.for({ seconds \| minutes \| hours \| days })` / `wait.until({ date })` | `sleep()` | Import from `workflow`. |
54
- | `wait.forToken({ timeout })` | `createHook()` + `Promise.race` with `sleep()` | Hooks carry a typed token. |
55
- | `tasks.trigger()` / `triggerAndWait()` | `start()` and `getRun(runId).returnValue` | Call `start()` directly; wrap `getRun()` collection in a `"use step"` function. |
56
- | `batch.triggerAndWait()` | `Promise.all(runIds.map(collectResult))` | Fan out via standard concurrency. |
57
- | `AbortTaskRunError` | `FatalError` | Stops retries immediately. |
58
- | `retry.onThrow` / `retry.fetch` | `RetryableError`, `FatalError`, `maxRetries` | Retry count lives on the step via `myStep.maxRetries = N` (default 3). Control delay between attempts by throwing `new RetryableError(msg, { retryAfter: '5s' })` — there is no built-in exponential helper; compute the delay yourself based on `getStepMetadata().attempt` if you need one. |
59
- | `metadata.stream()` / Realtime | `getWritable()` / `getWritable({ namespace })` | For granular business status (progress updates, current-stage messages), prefer writing to `getWritable({ namespace: 'status' })` from a step and reading from the end of the named stream on the client. Use `getRun(runId).status` for terminal/lifecycle state only. |
60
- | Self-hosted worker + dashboard | Managed execution + built-in UI | No worker fleet to operate. |
61
-
62
- ## Translate your first workflow
63
-
64
- <Callout type="warn">
65
- trigger.dev's `task.run` body has full Node.js access. The SDK's `'use workflow'` body runs in a sandboxed VM — side effects (I/O, `Date.now()`, `Math.random()`, DB, fetch) must live inside `'use step'` functions. Orchestration stays in the workflow body.
66
- </Callout>
67
-
68
- Start with the shell. trigger.dev wraps the handler in `task()`; the Workflow SDK marks the function with a directive.
69
-
70
- ```typescript title="trigger/order.ts (trigger.dev)"
71
- import { task } from '@trigger.dev/sdk';
72
-
73
- export const processOrder = task({
74
- id: 'process-order',
75
- run: async (payload: { orderId: string }) => {
76
- return { orderId: payload.orderId, status: 'completed' };
77
- },
78
- });
79
- ```
80
-
81
- ```typescript title="trigger/order.ts (Workflow SDK)"
82
- export async function processOrder(orderId: string) {
83
- 'use workflow'; // [!code highlight]
84
- return { orderId, status: 'completed' };
85
- }
86
- ```
87
-
88
- **What changed:** the `task()` factory and its `id` field disappear. The function is a plain export tagged with `"use workflow"`.
89
-
90
- ### Add a step
91
-
92
- The body of `run` becomes one or more `"use step"` functions.
93
-
94
- ```typescript title="workflow/workflows/order.ts"
95
- async function loadOrder(orderId: string) {
96
- 'use step'; // [!code highlight]
97
- const res = await fetch(`https://example.com/api/orders/${orderId}`);
98
- return res.json() as Promise<{ id: string }>;
99
- }
100
- ```
101
-
102
- Call it from the workflow with a plain `await`. Each additional side effect (`reserveInventory`, `chargePayment`) follows the same shape.
103
-
104
- ### Start the run
105
-
106
- trigger.dev dispatches with `tasks.trigger<typeof processOrder>('process-order', { orderId })`. The Workflow SDK calls `start()` directly:
107
-
108
- ```typescript title="app/api/orders/route.ts"
109
- import { start } from 'workflow/api';
110
- import { processOrder } from '@/workflows/order';
111
-
112
- export async function POST(request: Request) {
113
- const { orderId } = (await request.json()) as { orderId: string };
114
- const run = await start(processOrder, [orderId]); // [!code highlight]
115
- return Response.json({ runId: run.runId });
116
- }
117
- ```
118
-
119
- No id lookup, no API key, no separate worker. `start()` returns a handle immediately.
120
-
121
- ## Wait for an external signal
122
-
123
- `wait.forToken()` becomes `createHook()` plus `await`.
124
-
125
- {/* @skip-typecheck: trigger.dev SDK types not available */}
126
- ```typescript title="workflow/workflows/refund.ts (trigger.dev, abbreviated)"
127
- // import { wait } from '@trigger.dev/sdk';
128
- const token = await wait.createToken({ timeout: '7d' });
129
- const approval = await wait.forToken<{ approved: boolean }>(token.id).unwrap();
130
- // External system resumes with: await wait.completeToken(token.id, { approved: true });
131
- ```
132
-
133
- {/* @skip-typecheck: snippet without imports */}
134
- ```typescript title="workflow/workflows/refund.ts (Workflow SDK)"
135
- using approval = createHook<{ approved: boolean }>({ // [!code highlight]
136
- token: `refund:${refundId}:approval`,
137
- });
138
- const payload = await approval;
139
- ```
140
-
141
- **What changed:** the platform-issued opaque token becomes an app-owned string. The caller that resumes the run supplies that same string, so there is no token lookup. (trigger.dev also exposes `token.url` for external callers; the SDK analog is `createWebhook().url`).
142
-
143
- ### Resume from an API route
144
-
145
- There are two shapes of resume, and `wait.forToken` can map to either:
146
-
147
- - **Server-side resume (known token):** `createHook<T>({ token: 'business-token' })` + `resumeHook(token, payload)` from an API route. Use this when your app knows the token shape and controls the resume call.
148
- - **Third-party callback URL (generated token):** `createWebhook({ respondWith: 'default' })` + pass `webhook.url` to the external system. The external system hits the URL to resume.
149
-
150
- See [`/docs/foundations/hooks`](/docs/foundations/hooks) for both surfaces.
151
-
152
- trigger.dev completes a token with `wait.completeToken(tokenId, { approved })`. The SDK equivalent is `resumeHook`:
153
-
154
- ```typescript title="app/api/refunds/[refundId]/approve/route.ts"
155
- import { resumeHook } from 'workflow/api';
156
-
157
- export async function POST(request: Request, { params }: { params: Promise<{ refundId: string }> }) {
158
- const { refundId } = await params;
159
- const { approved } = (await request.json()) as { approved: boolean };
160
- await resumeHook(`refund:${refundId}:approval`, { approved }); // [!code highlight]
161
- return Response.json({ ok: true });
162
- }
163
- ```
164
-
165
- ### Add a timeout and branch on the payload
166
-
167
- trigger.dev's `timeout: '7d'` option maps to a `Promise.race()` with `sleep()`:
168
-
169
- {/* @skip-typecheck: continuation snippet */}
170
- ```typescript title="workflow/workflows/refund.ts"
171
- const result = await Promise.race([
172
- approval.then((p) => ({ type: 'decision' as const, approved: p.approved })),
173
- sleep('7d').then(() => ({ type: 'timeout' as const })), // [!code highlight]
174
- ]);
175
-
176
- if (result.type === 'timeout') return { refundId, status: 'timed-out' };
177
- if (!result.approved) return { refundId, status: 'rejected' };
178
- return { refundId, status: 'approved' };
179
- ```
180
-
181
- <Callout type="info">
182
- A hook is an inbound write channel. The caller that knows the token resumes the run with a typed payload. For granular business status (progress updates, current-stage messages), prefer writing to `getWritable({ namespace: 'status' })` from a step and reading from the end of the named stream on the client. Use `getRun(runId).status` for terminal/lifecycle state only.
183
- </Callout>
184
-
185
- ## Spawn a child workflow
186
-
187
- `triggerAndWait()` splits into spawn and collect. In v5, call `start()` directly from the workflow to spawn the child. Wrap `getRun()` and `returnValue` access in a `"use step"` function when you need to collect the result.
188
-
189
- You can return either the full `Run` object (enables deep-linking) or just `run.runId` (simpler). The runtime serializes `Run` to its `runId` in the event log either way.
190
-
191
- Await the result in a step, then orchestrate both from the parent:
192
-
193
- ```typescript title="workflow/workflows/parent.ts"
194
- import { getRun, start } from 'workflow/api';
195
-
196
- async function collectResult(runId: string) {
197
- 'use step';
198
- const run = getRun(runId);
199
- return (await run.returnValue) as { item: string; result: string }; // [!code highlight]
200
- }
201
-
202
- export async function parentWorkflow(item: string) {
203
- 'use workflow';
204
- const child = await start(childWorkflow, [item]); // [!code highlight]
205
- return await collectResult(child.runId);
206
- }
207
- ```
208
-
209
- To fan out, call `start()` inside a loop, then `Promise.all` the `collectResult` calls. That replaces `batch.triggerAndWait()`.
210
-
211
- `Promise.all` rejects on first failure; use `Promise.allSettled` if you need batch-mode error tolerance similar to trigger.dev's `{ ok, output, error }` per-run result.
212
-
213
- ## What you stop operating
214
-
215
- Dropping the trigger.dev SDK removes several moving parts:
216
-
217
- - **No task registry or `id` strings.** Workflow files carry directive annotations and export plain functions.
218
- - **No `@trigger.dev/sdk` client or API key.** `start()` launches runs directly from API routes or server actions.
219
- - **No worker fleet or self-hosted instance.** The runtime schedules execution inside the app's deploy target.
220
- - **No separate Realtime channel.** `getWritable()` streams updates from steps over the run's durable stream.
221
- - **No dashboard account.** The built-in observability UI (`npx workflow web`) reads the same event log the runtime writes.
222
-
223
- Workflows suspended on `sleep()` or a hook consume no compute until resumed.
224
-
225
- ## Step-by-step first migration
226
-
227
- Pick one trigger.dev task and migrate it end-to-end before touching the rest. The steps below describe the smallest viable path.
228
-
229
- ### Step 1: Install the Workflow SDK
230
-
231
- Add the runtime. Framework integrations (Next.js, Nitro, Nuxt, SvelteKit, Astro, Nest) are subpath exports of the same `workflow` package, e.g. `workflow/next` — no additional install needed.
232
-
233
- ```bash
234
- pnpm add workflow
235
- ```
236
-
237
- ### Step 2: Convert `task()` to a `"use workflow"` export
238
-
239
- Drop the factory call and the `id`. Move the handler body up and replace the payload object with typed function arguments.
240
-
241
- ```ts title="workflows/order.ts"
242
- // Before (trigger.dev)
243
- // export const processOrder = task({
244
- // id: "process-order",
245
- // run: async ({ orderId }: { orderId: string }) => { ... },
246
- // });
247
-
248
- // After (Workflow SDK)
249
- export async function processOrder(orderId: string) {
250
- "use workflow"; // [!code highlight]
251
- // ...
252
- }
253
- ```
254
-
255
- ### Step 3: Convert the task body into `"use step"` named functions
256
-
257
- Each side effect becomes a named function with `"use step"` on the first line. The workflow calls them with a plain `await`. `schemaTask()` validation moves to the call site: validate with zod before calling `start()`.
258
-
259
- ```ts
260
- async function loadOrder(id: string) {
261
- "use step"; // [!code highlight]
262
- return fetch(`/api/orders/${id}`).then((r) => r.json());
263
- }
264
- ```
265
-
266
- ### Step 4: Replace `wait.*` with hooks and `sleep`
267
-
268
- - `wait.for({ seconds | minutes | hours | days })` / `wait.until({ date })` → `sleep('5m')` or `sleep(date)` from `workflow`.
269
- - `wait.forToken(token)` → `createHook({ token })` + `await`. Complete it with `resumeHook(token, payload)` from an API route.
270
- - `wait.forToken({ timeout })` → `Promise.race([hook, sleep(timeout)])`.
271
- - `triggerAndWait(payload)` → call `start(child, [payload])` from the workflow and return the `Run` object, then read the result with a step that calls `getRun(runId).returnValue`.
272
-
273
- ### Step 5: Start runs from the app
274
-
275
- Delete the trigger.dev client setup. Launch runs directly from an API route or server action:
276
-
277
- ```ts title="app/api/orders/route.ts"
278
- import { start } from "workflow/api";
279
- import { processOrder } from "@/workflows/order";
280
-
281
- export async function POST(req: Request) {
282
- const { orderId } = await req.json();
283
- const run = await start(processOrder, [orderId]);
284
- return Response.json({ runId: run.runId });
285
- }
286
- ```
287
-
288
- ### Step 6: Retire trigger.dev infrastructure
289
-
290
- Remove the `@trigger.dev/sdk` dependency, the `trigger.config.ts` file, the `trigger/` directory, and any self-hosted worker deployment. Delete dashboard API keys from the environment. Verify the run in `npx workflow web` before shipping.
291
-
292
- ## Retries on steps
293
-
294
- Retry count lives on the step function itself. Set it as a property on the step:
295
-
296
- ```typescript
297
- async function chargePayment(orderId: string) {
298
- "use step";
299
- // ...
300
- }
301
- chargePayment.maxRetries = 5;
302
- ```
303
-
304
- Throw `new RetryableError(msg, { retryAfter: '5s' })` to control delay between attempts, or `FatalError` to stop retries immediately. See [`/docs/foundations/errors-and-retries`](/docs/foundations/errors-and-retries).
305
-
306
- ## Features without a 1:1 equivalent
307
-
308
- - **`schedules.task()` / cron triggers.** The SDK has no built-in scheduler. Trigger runs from Vercel Cron or a system cron calling `start()`.
309
- - **Concurrency keys / queue concurrency limits.** No direct analog. Enforce limits inside steps (semaphores, external coordinator) or debounce at the publisher.
310
- - **`machine` presets / custom images.** Machine specs are per-task in trigger.dev; in the SDK, function resources are per-deployment (configure via your hosting platform).
311
- - **Realtime / `subscribeToRun`.** Use `getRun(runId).getReadable()` plus named `getWritable()` streams for live progress.
312
- - **`onFailure` lifecycle hook.** No equivalent. Handle cleanup in the workflow body with a try/catch + compensation-stack pattern.
313
- - **Trigger.dev dashboard.** Workflow SDK ships `npx workflow web` for local inspection and the Vercel Observability tab for deployed runs.
314
-
315
- ## Quick-start checklist
316
-
317
- - Replace `task({ id, run })` with a `"use workflow"` function; launch it with `start()`.
318
- - Convert each task body into named `"use step"` functions.
319
- - Swap `wait.for` / `wait.until` for `sleep()` from `workflow`.
320
- - Swap `wait.forToken` for `createHook()` (internal) or `createWebhook()` (HTTP).
321
- - Model `wait.forToken` timeouts as `Promise.race()` between the hook and `sleep()`.
322
- - Replace `triggerAndWait()` with direct `start()` calls and a `"use step"` wrapper around `getRun()` when collecting results.
323
- - Replace `batch.triggerAndWait()` with `Promise.all` over the collected child `Run` handles.
324
- - Move `schemaTask` validation to the call site; pass typed arguments into the workflow.
325
- - Replace `AbortTaskRunError` with `FatalError`; model retries per step with `RetryableError` and `maxRetries`.
326
- - Use `getStepMetadata().stepId` as the idempotency key for external side effects.
327
- - Replace `metadata.stream()` and Realtime with `getWritable()`.
328
- - Remove the `@trigger.dev/sdk` dependency, `trigger.config.ts`, and any self-hosted worker.
329
- - Deploy and verify runs end-to-end with the built-in observability UI.
330
-
331
- ---
332
- *Verified against `workflow@5.0.0-beta.1` and `@trigger.dev/sdk` v3 on 2026-04-16.*