@upstash/workflow 1.4.0 → 1.5.0

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 (223) hide show
  1. package/README.md +9 -0
  2. package/astro.d.mts +19 -2
  3. package/astro.d.ts +19 -2
  4. package/astro.js +670 -159
  5. package/astro.mjs +1 -1
  6. package/{chunk-DRHEHWMS.mjs → chunk-J3PXPHSB.mjs} +828 -317
  7. package/cloudflare.d.mts +17 -2
  8. package/cloudflare.d.ts +17 -2
  9. package/cloudflare.js +670 -159
  10. package/cloudflare.mjs +1 -1
  11. package/docs/agents/examples.mdx +8 -0
  12. package/docs/agents/features.mdx +374 -0
  13. package/docs/agents/getting-started.mdx +139 -0
  14. package/docs/agents/overview.mdx +40 -0
  15. package/docs/agents/patterns/evaluator-optimizer.mdx +72 -0
  16. package/docs/agents/patterns/orchestrator-workers.mdx +95 -0
  17. package/docs/agents/patterns/parallelization.mdx +77 -0
  18. package/docs/agents/patterns/prompt-chaining.mdx +84 -0
  19. package/docs/basics/best-practices/at-least-one-step.mdx +57 -0
  20. package/docs/basics/best-practices/business-logic-in-steps.mdx +52 -0
  21. package/docs/basics/best-practices/deterministic-code.mdx +132 -0
  22. package/docs/basics/best-practices/idempotency.mdx +38 -0
  23. package/docs/basics/best-practices/nested-context-methods.mdx +38 -0
  24. package/docs/basics/best-practices/overview.mdx +35 -0
  25. package/docs/basics/best-practices/promise-any.mdx +9 -0
  26. package/docs/basics/best-practices/return-step-results.mdx +80 -0
  27. package/docs/basics/best-practices/workflow-limits.mdx +62 -0
  28. package/docs/basics/client/cancel.mdx +137 -0
  29. package/docs/basics/client/dlq/callback.mdx +21 -0
  30. package/docs/basics/client/dlq/delete.mdx +120 -0
  31. package/docs/basics/client/dlq/list.mdx +96 -0
  32. package/docs/basics/client/dlq/restart.mdx +164 -0
  33. package/docs/basics/client/dlq/resume.mdx +167 -0
  34. package/docs/basics/client/logs.mdx +139 -0
  35. package/docs/basics/client/notify.mdx +79 -0
  36. package/docs/basics/client/trigger.mdx +139 -0
  37. package/docs/basics/client/waiters.mdx +31 -0
  38. package/docs/basics/client.mdx +40 -0
  39. package/docs/basics/how.mdx +65 -0
  40. package/docs/basics/serve/advanced.mdx +435 -0
  41. package/docs/basics/serve.mdx +142 -0
  42. package/docs/changelog.mdx +174 -0
  43. package/docs/examples/allInOne.mdx +377 -0
  44. package/docs/examples/authWebhook.mdx +567 -0
  45. package/docs/examples/customRetry.mdx +309 -0
  46. package/docs/examples/customerOnboarding.mdx +230 -0
  47. package/docs/examples/dynamicWorkflow.mdx +203 -0
  48. package/docs/examples/eCommerceOrderFulfillment.mdx +281 -0
  49. package/docs/examples/imageProcessing.mdx +339 -0
  50. package/docs/examples/paymentRetry.mdx +438 -0
  51. package/docs/examples/waitForEvent.mdx +201 -0
  52. package/docs/features/dlq/callback.mdx +42 -0
  53. package/docs/features/dlq/delete.mdx +29 -0
  54. package/docs/features/dlq/restart.mdx +33 -0
  55. package/docs/features/dlq/resume.mdx +37 -0
  56. package/docs/features/dlq.mdx +39 -0
  57. package/docs/features/failure-callback.mdx +102 -0
  58. package/docs/features/failureFunction/advanced.mdx +36 -0
  59. package/docs/features/failureFunction/reliability.mdx +33 -0
  60. package/docs/features/flow-control/monitor.mdx +22 -0
  61. package/docs/features/flow-control/parallelism.mdx +45 -0
  62. package/docs/features/flow-control/rate-period.mdx +46 -0
  63. package/docs/features/flow-control.mdx +164 -0
  64. package/docs/features/invoke/serveMany.mdx +109 -0
  65. package/docs/features/invoke.mdx +39 -0
  66. package/docs/features/notify.mdx +127 -0
  67. package/docs/features/parallel-steps.mdx +41 -0
  68. package/docs/features/retries/prevent-retries.mdx +140 -0
  69. package/docs/features/retries.mdx +93 -0
  70. package/docs/features/wait-for-event.mdx +104 -0
  71. package/docs/features/wait.mdx +44 -0
  72. package/docs/features/webhooks.mdx +116 -0
  73. package/docs/getstarted.mdx +200 -0
  74. package/docs/howto/cancel.mdx +50 -0
  75. package/docs/howto/changes.mdx +33 -0
  76. package/docs/howto/configure.mdx +42 -0
  77. package/docs/howto/failures.mdx +185 -0
  78. package/docs/howto/get-token.mdx +18 -0
  79. package/docs/howto/local-development/development-server.mdx +130 -0
  80. package/docs/howto/local-development/local-tunnel.mdx +73 -0
  81. package/docs/howto/middlewares.mdx +263 -0
  82. package/docs/howto/migrations.mdx +335 -0
  83. package/docs/howto/multi-region.mdx +107 -0
  84. package/docs/howto/parallel-runs.mdx +52 -0
  85. package/docs/howto/readonly-token.mdx +19 -0
  86. package/docs/howto/realtime/basic.mdx +315 -0
  87. package/docs/howto/realtime/human-in-the-loop.mdx +454 -0
  88. package/docs/howto/redact-fields.mdx +61 -0
  89. package/docs/howto/retry-now.mdx +41 -0
  90. package/docs/howto/schedule.mdx +104 -0
  91. package/docs/howto/security.mdx +143 -0
  92. package/docs/howto/singleton.mdx +137 -0
  93. package/docs/howto/start.mdx +69 -0
  94. package/docs/howto/use-webhooks.mdx +256 -0
  95. package/docs/integrations/aisdk.mdx +316 -0
  96. package/docs/integrations/anthropic.mdx +51 -0
  97. package/docs/integrations/datadog.mdx +69 -0
  98. package/docs/integrations/openai.mdx +87 -0
  99. package/docs/integrations/prometheus.mdx +65 -0
  100. package/docs/integrations/resend.mdx +82 -0
  101. package/docs/llms-txt.mdx +4 -0
  102. package/docs/openapi.yaml +2944 -0
  103. package/docs/pricing.mdx +22 -0
  104. package/docs/quickstarts/astro.mdx +185 -0
  105. package/docs/quickstarts/cloudflare-workers.mdx +190 -0
  106. package/docs/quickstarts/express.mdx +190 -0
  107. package/docs/quickstarts/fastapi.mdx +282 -0
  108. package/docs/quickstarts/flask.mdx +282 -0
  109. package/docs/quickstarts/hono.mdx +221 -0
  110. package/docs/quickstarts/nextjs-fastapi.mdx +147 -0
  111. package/docs/quickstarts/nextjs-flask.mdx +147 -0
  112. package/docs/quickstarts/nuxt.mdx +169 -0
  113. package/docs/quickstarts/platforms.mdx +78 -0
  114. package/docs/quickstarts/solidjs.mdx +161 -0
  115. package/docs/quickstarts/svelte.mdx +170 -0
  116. package/docs/quickstarts/tanstack-start.mdx +205 -0
  117. package/docs/quickstarts/vercel-nextjs.mdx +233 -0
  118. package/docs/roadmap.mdx +8 -0
  119. package/docs/sdk/workflow-js.mdx +4 -0
  120. package/docs/sdk/workflow-py.mdx +4 -0
  121. package/docs/steps/api.mdx +64 -0
  122. package/docs/steps/call.mdx +183 -0
  123. package/docs/steps/cancel.mdx +25 -0
  124. package/docs/steps/createWebhook.mdx +40 -0
  125. package/docs/steps/invoke.mdx +100 -0
  126. package/docs/steps/notify.mdx +105 -0
  127. package/docs/steps/run.mdx +150 -0
  128. package/docs/steps/sleep.mdx +97 -0
  129. package/docs/steps/sleepUntil.mdx +88 -0
  130. package/docs/steps/waitForEvent.mdx +60 -0
  131. package/docs/steps/waitForWebhook.mdx +78 -0
  132. package/docs/steps.mdx +108 -0
  133. package/docs/troubleshooting/general.mdx +331 -0
  134. package/docs/troubleshooting/vercel.mdx +82 -0
  135. package/express.d.mts +19 -2
  136. package/express.d.ts +19 -2
  137. package/express.js +670 -159
  138. package/express.mjs +1 -1
  139. package/h3.d.mts +19 -2
  140. package/h3.d.ts +19 -2
  141. package/h3.js +670 -159
  142. package/h3.mjs +1 -1
  143. package/hono.d.mts +17 -2
  144. package/hono.d.ts +17 -2
  145. package/hono.js +670 -159
  146. package/hono.mjs +1 -1
  147. package/index.d.mts +50 -21
  148. package/index.d.ts +50 -21
  149. package/index.js +686 -171
  150. package/index.mjs +17 -13
  151. package/nextjs.d.mts +40 -2
  152. package/nextjs.d.ts +40 -2
  153. package/nextjs.js +670 -159
  154. package/nextjs.mjs +1 -1
  155. package/package.json +1 -1
  156. package/react-router.d.mts +16 -2
  157. package/react-router.d.ts +16 -2
  158. package/react-router.js +670 -159
  159. package/react-router.mjs +1 -1
  160. package/{serve-many-CG3BFvO3.d.mts → serve-many-BKukvLNl.d.mts} +1 -1
  161. package/{serve-many-iJF1IUXk.d.ts → serve-many-CrLKQpuZ.d.ts} +1 -1
  162. package/solidjs.d.mts +10 -1
  163. package/solidjs.d.ts +10 -1
  164. package/solidjs.js +670 -159
  165. package/solidjs.mjs +1 -1
  166. package/src/platforms/astro.ts +84 -0
  167. package/src/platforms/cloudflare.ts +127 -0
  168. package/src/platforms/express.ts +147 -0
  169. package/src/platforms/h3.ts +105 -0
  170. package/src/platforms/hono.ts +103 -0
  171. package/src/platforms/nextjs.ts +193 -0
  172. package/src/platforms/react-router.ts +92 -0
  173. package/src/platforms/solidjs.ts +59 -0
  174. package/src/platforms/svelte.ts +99 -0
  175. package/src/platforms/tanstack.ts +96 -0
  176. package/src/src/client/dlq.ts +387 -0
  177. package/src/src/client/filter-types.ts +166 -0
  178. package/src/src/client/index.ts +350 -0
  179. package/src/src/client/types.ts +501 -0
  180. package/src/src/client/utils.ts +307 -0
  181. package/src/src/constants.ts +82 -0
  182. package/src/src/context/api/anthropic.ts +58 -0
  183. package/src/src/context/api/base.ts +52 -0
  184. package/src/src/context/api/index.ts +24 -0
  185. package/src/src/context/api/openai.ts +125 -0
  186. package/src/src/context/api/resend.ts +57 -0
  187. package/src/src/context/auto-executor.ts +707 -0
  188. package/src/src/context/context.ts +681 -0
  189. package/src/src/context/index.ts +1 -0
  190. package/src/src/context/provider.ts +37 -0
  191. package/src/src/context/steps.ts +965 -0
  192. package/src/src/error.ts +203 -0
  193. package/src/src/index.ts +13 -0
  194. package/src/src/middleware/default-callbacks.ts +20 -0
  195. package/src/src/middleware/index.ts +2 -0
  196. package/src/src/middleware/logging.ts +39 -0
  197. package/src/src/middleware/manager.ts +148 -0
  198. package/src/src/middleware/middleware.ts +46 -0
  199. package/src/src/middleware/types.ts +72 -0
  200. package/src/src/qstash/headers.ts +397 -0
  201. package/src/src/qstash/step-config.ts +268 -0
  202. package/src/src/qstash/submit-steps.ts +284 -0
  203. package/src/src/serve/authorization.ts +118 -0
  204. package/src/src/serve/index.ts +475 -0
  205. package/src/src/serve/multi-region/handlers.ts +225 -0
  206. package/src/src/serve/multi-region/utils.ts +88 -0
  207. package/src/src/serve/options.ts +241 -0
  208. package/src/src/serve/serve-many.ts +117 -0
  209. package/src/src/serve/utils.ts +11 -0
  210. package/src/src/types.ts +590 -0
  211. package/src/src/utils.ts +141 -0
  212. package/src/src/workflow-parser.ts +472 -0
  213. package/src/src/workflow-requests.ts +575 -0
  214. package/svelte.d.mts +17 -2
  215. package/svelte.d.ts +17 -2
  216. package/svelte.js +670 -159
  217. package/svelte.mjs +1 -1
  218. package/tanstack.d.mts +15 -2
  219. package/tanstack.d.ts +15 -2
  220. package/tanstack.js +670 -159
  221. package/tanstack.mjs +1 -1
  222. package/{types-CekOpKvz.d.ts → types-CrgK5P6p.d.mts} +372 -32
  223. package/{types-CekOpKvz.d.mts → types-CrgK5P6p.d.ts} +372 -32
@@ -0,0 +1,143 @@
1
+ ---
2
+ title: "Secure a Workflow"
3
+ ---
4
+
5
+ To prevent unauthorized access to your workflow endpoint, you can add an authorization layer.
6
+ Upstash Workflow supports two approaches:
7
+
8
+ - **Built-in request verification** (recommended)
9
+ - **Custom authorization method**
10
+
11
+ ### Built-in request verification (recommended)
12
+
13
+ Upstash Workflow provides a built-in mechanism to secure your workflow endpoint by verifying request signatures.
14
+ Every request to your endpoint include a valid `Upstash-Signature` header.
15
+
16
+ How it works:
17
+
18
+ 1. Upstash Workflow automatically adds the `Upstash-Signature` header to every request.
19
+ This signature is generated using your signing keys.
20
+
21
+ 2. When this mechanism is enabled, the SDK verifies that the signature is valid before processing the request.
22
+
23
+ This ensures that only requests originating from Upstash Workflow are processed.
24
+
25
+ To enable this verification, set the following environment variables in your application:
26
+
27
+ ```bash .env
28
+ QSTASH_CURRENT_SIGNING_KEY=xxxxxxxxx
29
+ QSTASH_NEXT_SIGNING_KEY=xxxxxxxxx
30
+ ```
31
+
32
+ You can find the values in Upstash Workflow dashboard.
33
+
34
+ <Frame>
35
+ <img src="/img/qstash-workflow/qstash_signing_keys.png" alt="QStash signing keys in the Upstash Console" />
36
+ </Frame>
37
+
38
+ <Info>
39
+ For edge cases where environment variables cannot be used, you can explicitly create and pass a `Receiver` object to verify request signatures:
40
+
41
+ <CodeGroup>
42
+
43
+ ```typescript TypeScript
44
+ import { Receiver } from "@upstash/qstash";
45
+ import { serve } from "@upstash/workflow/nextjs";
46
+
47
+ export const { POST } = serve(
48
+ async (context) => { ... },
49
+ {
50
+ receiver: new Receiver({
51
+ currentSigningKey: "<QSTASH_CURRENT_SIGNING_KEY>",
52
+ nextSigningKey: "<QSTASH_NEXT_SIGNING_KEY>",
53
+ }),
54
+ }
55
+ );
56
+ ```
57
+
58
+ ```python Python
59
+ from qstash import Receiver
60
+
61
+ @serve.post(
62
+ "/api/example",
63
+ receiver=Receiver(
64
+ current_signing_key=os.environ["QSTASH_CURRENT_SIGNING_KEY"],
65
+ next_signing_key=os.environ["QSTASH_NEXT_SIGNING_KEY"],
66
+ ),
67
+ )
68
+ async def example(context: AsyncWorkflowContext[str]) -> None:
69
+ ...
70
+
71
+ ```
72
+ </CodeGroup>
73
+ </Info>
74
+
75
+ ## Custom Authorization Method
76
+
77
+ You can implement your own authorization mechanism with Upstash Workflow.
78
+
79
+ The context object provides access to the initial request headers and payload on every workflow step.
80
+ You can use them to pass your custom authentication token to verify the requests.
81
+
82
+ <CodeGroup>
83
+
84
+ ```typescript TypeScript
85
+ import { serve } from "@upstash/workflow/nextjs";
86
+
87
+ export const { POST } = serve(
88
+ async (context) => {
89
+ // 👇 Extract Bearer token form the request headers
90
+ const authHeader = context.headers.get("authorization");
91
+ const bearerToken = authHeader?.split(" ")[1];
92
+
93
+ // 👇 Use your authentication function to verify the token
94
+ if (!isValid(bearerToken)) {
95
+ console.error("Authentication failed.");
96
+ return;
97
+ }
98
+
99
+ // Your workflow steps..
100
+ },
101
+ {
102
+ failureFunction: async () => {
103
+ // 👇 Same auth check for failure function
104
+ const authHeader = context.headers.get("authorization");
105
+ const bearerToken = authHeader?.split(" ")[1];
106
+
107
+ if (!isValid(bearerToken)) {
108
+ // ...
109
+ }
110
+ },
111
+ }
112
+ );
113
+ ```
114
+
115
+ ```python Python
116
+ from fastapi import FastAPI
117
+ from upstash_workflow.fastapi import Serve
118
+ from upstash_workflow import AsyncWorkflowContext
119
+
120
+ app = FastAPI()
121
+ serve = Serve(app)
122
+
123
+
124
+ @serve.post("/api/example")
125
+ async def example(context: AsyncWorkflowContext[str]) -> None:
126
+ auth_header = context.headers.get("authorization")
127
+ bearer_token = auth_header.split(" ")[1] if auth_header else None
128
+
129
+ if not is_valid(bearer_token):
130
+ print("Authentication failed.")
131
+ return
132
+
133
+ # Your workflow steps...
134
+
135
+ ```
136
+
137
+ </CodeGroup>
138
+
139
+ <Warning>
140
+ If you implement custom authorization in your workflow route, you should also include the same authorization check in the failure function.
141
+
142
+ The failure function executes independently of the route function, so without this check, unauthorized requests could trigger the failure function
143
+ </Warning>
@@ -0,0 +1,137 @@
1
+ ---
2
+ title: "Singleton Workflows"
3
+ description: "Make sure only one run of a workflow is in progress at a time by reusing the same workflowRunId."
4
+ ---
5
+
6
+ A singleton workflow has at most one run in progress at a time. A nightly sync,
7
+ a per-user onboarding flow or a cache rebuild are typical examples: starting a
8
+ second copy while the first one is still running would do the same work twice.
9
+
10
+ You get this behavior by starting every run with the **same `workflowRunId`**.
11
+ A run ID is reserved while its run is in progress, and released once the run
12
+ finishes, fails or is cancelled.
13
+
14
+ <Note>
15
+ Singleton workflows require `@upstash/workflow` **1.4.0** or later.
16
+
17
+ With older versions, a run started again with the same `workflowRunId` and the
18
+ same body within 10 minutes of the previous one is deduplicated by QStash: it
19
+ either doesn't start or gets stuck on its first step.
20
+ </Note>
21
+
22
+ There are two ways to handle a new trigger while a run is in progress:
23
+
24
+ | Pattern | When a run is already in progress |
25
+ | --- | --- |
26
+ | [Keep the running one](#keep-the-running-one) | The new trigger is rejected. The existing run continues. |
27
+ | [Replace the running one](#replace-the-running-one) | The running run is cancelled and a new one starts. |
28
+
29
+ In both patterns, a trigger after the previous run has ended starts a new run,
30
+ even with exactly the same body.
31
+
32
+ ## Keep the running one
33
+
34
+ Trigger the workflow with a fixed `workflowRunId`. If a run with that ID is
35
+ still in progress, `client.trigger` throws and no new run is started.
36
+
37
+ ```ts
38
+ import { Client } from "@upstash/workflow";
39
+ import { QstashError } from "@upstash/qstash";
40
+
41
+ const client = new Client({ token: "<QSTASH_TOKEN>" });
42
+
43
+ try {
44
+ const { workflowRunId } = await client.trigger({
45
+ url: "https://<YOUR_WORKFLOW_ENDPOINT>/nightly-sync",
46
+ workflowRunId: "nightly-sync",
47
+ body: { source: "crm" },
48
+ });
49
+ console.log(`started ${workflowRunId}`); // started wfr_nightly-sync
50
+ } catch (error) {
51
+ if (!(error instanceof QstashError) || error.status !== 400) {
52
+ throw error;
53
+ }
54
+
55
+ // a 400 can also mean an invalid request, so check that a run is in progress
56
+ const { runs } = await client.logs({
57
+ filter: { workflowRunId: "wfr_nightly-sync", state: "RUN_STARTED" },
58
+ });
59
+ if (runs.length === 0) {
60
+ throw error;
61
+ }
62
+ console.log("nightly-sync is already running, skipping");
63
+ }
64
+ ```
65
+
66
+ What `client.trigger` returns:
67
+
68
+ - **No run in progress:** a new run starts and the call resolves to
69
+ `{ workflowRunId: "wfr_nightly-sync" }`.
70
+ - **A run is in progress:** the call throws a `QstashError` with `status: 400`.
71
+ The running run is not affected.
72
+
73
+ QStash returns `400` for other invalid trigger requests too, such as a malformed
74
+ URL, so `status` alone doesn't tell you that the ID is taken. The example checks
75
+ with [`client.logs`](/workflow/basics/client/logs) that a run with the ID is in
76
+ progress before skipping. If that run ends between the two calls, `runs` is
77
+ empty and the error is rethrown, so you can retry the trigger.
78
+
79
+ <Note>
80
+ `QstashError` comes from `@upstash/qstash`, which `@upstash/workflow` depends
81
+ on. If your package manager doesn't let you import a dependency of a
82
+ dependency, add `@upstash/qstash` to your own dependencies. Keep it on the
83
+ version `@upstash/workflow` uses: with two copies of the package,
84
+ `instanceof QstashError` doesn't match.
85
+ </Note>
86
+
87
+ <Tip>
88
+ The ID you pass is prefixed with `wfr_`. `nightly-sync` becomes
89
+ `wfr_nightly-sync`, which is the ID you see in the logs and pass to
90
+ `client.cancel`.
91
+ </Tip>
92
+
93
+ ## Replace the running one
94
+
95
+ To always run the latest request, first cancel the existing run by its
96
+ prefixed run ID (for example, `wfr_rebuild-cache`), then start a new one with
97
+ the unprefixed `workflowRunId` (for example, `rebuild-cache`). If the previous
98
+ run hasn't finished yet, it is stopped and the new run takes its place.
99
+
100
+ ```ts
101
+ import { Client } from "@upstash/workflow";
102
+
103
+ const client = new Client({ token: "<QSTASH_TOKEN>" });
104
+
105
+ const { cancelled } = await client.cancel("wfr_rebuild-cache");
106
+ console.log(`cancelled ${cancelled} run(s)`);
107
+
108
+ const { workflowRunId } = await client.trigger({
109
+ url: "https://<YOUR_WORKFLOW_ENDPOINT>/rebuild-cache",
110
+ workflowRunId: "rebuild-cache",
111
+ body: { reason: "settings changed" },
112
+ });
113
+ console.log(`started ${workflowRunId}`); // started wfr_rebuild-cache
114
+ ```
115
+
116
+ What each call returns:
117
+
118
+ - `client.cancel` resolves to `{ cancelled: 1 }` when a run was in progress and
119
+ got cancelled, and to `{ cancelled: 0 }` when there was nothing to cancel. It
120
+ doesn't throw in either case, so you can call it unconditionally.
121
+ - `client.trigger` resolves to `{ workflowRunId: "wfr_rebuild-cache" }`. The
122
+ cancel is completed before `client.cancel` returns, so the ID is free when you
123
+ trigger the new run.
124
+
125
+ The cancelled run stops right away. If one of its steps is executing on your
126
+ endpoint at that moment, that code runs to the end, but its result is
127
+ discarded. Steps, waits and `context.call` results of the cancelled run are
128
+ never added to the new run, even though both runs share the same ID.
129
+
130
+ <Warning>
131
+ If two callers cancel and trigger the same ID at the same time, both cancels
132
+ can complete before either trigger. Then the first trigger starts a run, and
133
+ the second one throws the `400` error described in
134
+ [Keep the running one](#keep-the-running-one). Catch it and retry the cancel
135
+ and trigger if the latest request must win.
136
+ </Warning>
137
+
@@ -0,0 +1,69 @@
1
+ ---
2
+ title: "Start a Run"
3
+ ---
4
+
5
+ You’ve defined your workflow, and the final step is to trigger the endpoint!
6
+
7
+ There are two main ways to start your workflow:
8
+
9
+ ### Using `client.trigger` (Recommended)
10
+
11
+ We recommend using [`client.trigger`](/workflow/basics/client/trigger) to start your workflow.
12
+
13
+ <CodeGroup>
14
+ ```ts Single Workflow
15
+ import { Client } from "@upstash/workflow";
16
+
17
+ const client = new Client({ token: "<QSTASH_TOKEN>" })
18
+ const { workflowRunId } = await client.trigger({
19
+ url: "https://<YOUR_WORKFLOW_ENDPOINT>/<YOUR-WORKFLOW-ROUTE>",
20
+ body: "hello there!", // optional body
21
+ headers: { ... }, // optional headers
22
+ workflowRunId: "my-workflow", // optional workflow run id
23
+ retries: 3 // optional retries in the initial request
24
+ delay: "10s" // optional delay value
25
+ failureUrl: "https://<YOUR_FAILURE_URL>", // optional failure url
26
+ flowControl: { ... } // optional flow control
27
+ })
28
+
29
+ console.log(workflowRunId)
30
+ // prints wfr_my-workflow
31
+ ```
32
+
33
+ ```ts Multiple Workflows
34
+ import { Client } from "@upstash/workflow";
35
+
36
+ const client = new Client({ token: "<QSTASH_TOKEN>" })
37
+ const results = await client.trigger([
38
+ {
39
+ url: "<YOUR_WORKFLOW_ENDPOINT>",
40
+ // other options...
41
+ },
42
+ {
43
+ url: "<YOUR_WORKFLOW_ENDPOINT>",
44
+ // other options...
45
+ },
46
+ ])
47
+
48
+ console.log(results[0].workflowRunId)
49
+ // prints wfr_my-workflow
50
+ ```
51
+ </CodeGroup>
52
+
53
+ ### 2. Sending an HTTP Request
54
+
55
+ This approach is recommended for quick testing via curl during development.
56
+
57
+ You should **NOT** start the workflow run in production by direct calls to your endpoint.
58
+
59
+ ```bash
60
+ curl -X POST https://<YOUR_WORKFLOW_ENDPOINT>/<YOUR-WORKFLOW-ROUTE> \
61
+ -H "my-header: foo" \
62
+ -d '{"foo": "bar"}'
63
+ ```
64
+
65
+ <Warning>
66
+ If you’ve secured your endpoint with signing keys, only the `trigger` method will work. Direct calls to the endpoint (e.g., via `curl` or `fetch`) will not be possible since `Upstash-Signature` header is missing.
67
+
68
+ For more information, read [Secure a workflow](/workflow/howto/security) documentation.
69
+ </Warning>
@@ -0,0 +1,256 @@
1
+ ---
2
+ title: "Webhooks"
3
+ sidebarTitle: "Handle Webhooks"
4
+ ---
5
+
6
+ This guide explains how to handle webhooks effectively in your Upstash Workflow applications. We'll walk through:
7
+
8
+ - setting up webhook endpoints
9
+ - verifying webhook requests
10
+ - and processing webhook events
11
+
12
+ <Card
13
+ title="GitHub Repository"
14
+ icon="github"
15
+ href="https://github.com/upstash/workflow-js/tree/main/examples/nextjs-webhook-stripe"
16
+ horizontal
17
+ >
18
+ You can find the project source code on GitHub.
19
+ </Card>
20
+
21
+ ## Overview
22
+
23
+ Webhooks allow external services to notify your application when events occur. For example, you can use webhooks to receive notifications when a new order is placed in your e-commerce store, a new user signs up, or a new message is sent in your chat application.
24
+
25
+ Upstash Workflow provides a simple way to receive these events and trigger workflows based on the incoming data autonomously.
26
+
27
+ ### Setting Up Webhook Endpoints
28
+
29
+ #### Basic Setup
30
+
31
+ To create a webhook endpoint, use the `serve` function from `@upstash/workflow`:
32
+
33
+ <CodeGroup>
34
+
35
+ ```typescript TypeScript
36
+ import { serve } from "@upstash/workflow/nextjs";
37
+
38
+ export const { POST } = serve(
39
+ async (context) => {
40
+ // Your webhook handling logic here
41
+ },
42
+ {
43
+ initialPayloadParser: (payload) => {
44
+ return payload;
45
+ },
46
+ }
47
+ );
48
+ ```
49
+
50
+ ```python Python
51
+ from fastapi import FastAPI
52
+ from upstash_workflow.fastapi import Serve
53
+ from upstash_workflow import AsyncWorkflowContext
54
+
55
+ app = FastAPI()
56
+ serve = Serve(app)
57
+
58
+
59
+ def initial_payload_parser(payload):
60
+ return payload
61
+
62
+
63
+ @serve.post("/api/example", initial_payload_parser=initial_payload_parser)
64
+ async def example(context: AsyncWorkflowContext[str]) -> None:
65
+ # Your webhook handling logic here
66
+
67
+ ```
68
+
69
+ </CodeGroup>
70
+
71
+ #### Request Validation
72
+
73
+ Always validate incoming webhook requests to ensure they're legitimate. This way, no one other than the original webhook source can trigger your workflow. Here's an example using Clerk webhooks with Svix:
74
+
75
+ <CodeGroup>
76
+ ```typescript Validate and Parse in Workflow - TypeScript
77
+ export const { POST } = serve<string>(async (context) => {
78
+ const payloadString = context.requestPayload;
79
+ const headerPayload = context.headers;
80
+
81
+ let event: WebhookEvent;
82
+ try {
83
+ event = await validateRequest(payloadString, headerPayload);
84
+ } catch {
85
+ return
86
+ }
87
+
88
+ // Next steps based on the event
89
+
90
+ })
91
+
92
+ ```
93
+
94
+ ```python Validate and Parse in Workflow - Python
95
+ async def validate_request(payload_string: str, header_payload: dict):
96
+ # Validate the request
97
+ pass
98
+
99
+
100
+ @serve.post("/api/example")
101
+ async def example(context: AsyncWorkflowContext[str]) -> None:
102
+ payload_string = context.request_payload
103
+ header_payload = context.headers
104
+
105
+ try:
106
+ event = await validate_request(payload_string, header_payload)
107
+ except:
108
+ return
109
+
110
+ # Next steps based on the event
111
+
112
+ ```
113
+
114
+ ```typescript Validation Function - TypeScript
115
+ import { Webhook } from "svix";
116
+ import { WebhookEvent } from "@clerk/nextjs/server";
117
+
118
+ const webhookSecret = "YOUR_WEBHOOK_SECRET";
119
+
120
+ async function validateRequest(payloadString: string, headerPayload: Headers) {
121
+ const svixHeaders = {
122
+ "svix-id": headerPayload.get("svix-id") as string,
123
+ "svix-timestamp": headerPayload.get("svix-timestamp") as string,
124
+ "svix-signature": headerPayload.get("svix-signature") as string,
125
+ };
126
+ const wh = new Webhook(webhookSecret);
127
+ return wh.verify(payloadString, svixHeaders) as WebhookEvent;
128
+ }
129
+ ```
130
+
131
+ </CodeGroup>
132
+
133
+ ### Handling Webhook events
134
+
135
+ Use the context.run method to process webhook events in discrete, trackable steps:
136
+
137
+ <CodeGroup>
138
+
139
+ ```typescript TypeScript
140
+ export const { POST } = serve(async (context) => {
141
+ // ... Parse and validate the incoming request
142
+
143
+ const user = await context.run<false | UserPayload>(
144
+ "handle-webhook-event",
145
+ async () => {
146
+ if (event.type === "user.created") {
147
+ const { id: clerkUserId, email_addresses, first_name } = event.data;
148
+ const primaryEmail = email_addresses.find(
149
+ (email) => (email.id = event.data.primary_email_address_id)
150
+ );
151
+
152
+ if (!primaryEmail) {
153
+ return false;
154
+ }
155
+
156
+ return {
157
+ event: event.type,
158
+ userId: clerkUserId,
159
+ email: primaryEmail.email_address,
160
+ firstName: first_name,
161
+ } as UserPayload;
162
+ }
163
+ return false;
164
+ }
165
+ );
166
+ });
167
+ ```
168
+
169
+ ```python Python
170
+ @serve.post("/api/example")
171
+ async def example(context: AsyncWorkflowContext[str]) -> None:
172
+ # ... Parse and validate the incoming request
173
+
174
+ async def _handle_webhook_event():
175
+ if event.type == "user.created":
176
+ clerk_user_id = event.data["id"]
177
+ email_addresses = event.data["email_addresses"]
178
+ first_name = event.data["first_name"]
179
+
180
+ primary_email = next(
181
+ (
182
+ email
183
+ for email in email_addresses
184
+ if email.id == event.data["primary_email_address_id"]
185
+ ),
186
+ None,
187
+ )
188
+
189
+ if not primary_email:
190
+ return False
191
+
192
+ return {
193
+ "event": event.type,
194
+ "user_id": clerk_user_id,
195
+ "email": primary_email["email_address"],
196
+ "first_name": first_name,
197
+ }
198
+
199
+ return False
200
+
201
+ user = await context.run("handle-webhook-event", _handle_webhook_event)
202
+
203
+ ```
204
+
205
+ </CodeGroup>
206
+
207
+ After validating the webhook and extracting the initial user data, you'll often need to perform additional operations like creating customer records, sending welcome emails etc.
208
+
209
+ <CodeGroup>
210
+
211
+ ```typescript TypeScript
212
+ export const { POST } = serve(async (context) => {
213
+ // ... Previous validation and user data extraction
214
+
215
+ if (!user) {
216
+ return;
217
+ }
218
+
219
+ const customer = await context.run("create-stripe-customer", async () => {
220
+ return await stripe.customers.create({
221
+ email: user.email,
222
+ name: `${user.firstName} ${user.lastName}`,
223
+ metadata: {
224
+ userId: user.userId,
225
+ },
226
+ });
227
+ });
228
+
229
+ /// ... Additional steps
230
+ });
231
+ ```
232
+
233
+ ```python Python
234
+ @serve.post("/api/example")
235
+ async def example(context: AsyncWorkflowContext[str]) -> None:
236
+ # ... Previous validation and user data extraction
237
+
238
+ if not user:
239
+ return
240
+
241
+ async def _create_stripe_customer():
242
+ return await stripe.customers.create(
243
+ email=user["email"],
244
+ name=f"{user['first_name']} {user['last_name']}",
245
+ metadata={"user_id": user["user_id"]},
246
+ )
247
+
248
+ customer = await context.run("create-stripe-customer", _create_stripe_customer)
249
+
250
+ # ... Additional steps
251
+
252
+ ```
253
+
254
+ </CodeGroup>
255
+
256
+ You're now ready to perform any operation in the following steps.