createHook()
Creates a low-level hook primitive that can be used to resume a workflow run with arbitrary payloads.
Hooks allow external systems to send data to a paused workflow without the HTTP-specific constraints of webhooks. They're identified by a token and can receive any serializable payload.
import { createHook } from "workflow"
export async function hookWorkflow() {
"use workflow";
const hook = createHook();
const result = await hook; // Suspends the workflow until the hook is resumed
}API Signature
Parameters
| Name | Type | Description |
|---|---|---|
options | HookOptions | Configuration options for the hook. |
HookOptions
| Name | Type | Description |
|---|---|---|
token | string | Unique token that is used to associate with the hook. When specifying an explicit token, the token should be constructed with information that the dispatching side can reliably reconstruct the token with the information it has available. If not provided, a randomly generated token will be assigned. |
metadata | Serializable | Additional user-defined data to include with the hook payload. |
Returns
Hook<T>Hook
| Name | Type | Description |
|---|---|---|
token | string | The token used to identify this hook. |
The returned Hook object also implements AsyncIterable<T>, which allows you to iterate over incoming payloads using for await...of syntax.
Examples
Basic Usage
When creating a hook, you can specify a payload type to be used for automatic type safety.
import { createHook } from "workflow"
export async function approvalWorkflow() {
"use workflow";
const hook = createHook<{ approved: boolean; comment: string }>();
console.log('Send approval to token:', hook.token);
const result = await hook;
if (result.approved) {
console.log('Approved with comment:', result.comment);
}
}Customizing Tokens
Tokens are used to identify a specific hook. You can customize the token to be more specific to a use case.
import { createHook } from "workflow";
export async function slackBotWorkflow(channelId: string) {
"use workflow";
// Token constructed from channel ID
const hook = createHook<SlackMessage>({
token: `slack_webhook:${channelId}`,
});
for await (const message of hook) {
if (message.text === '/stop') {
break;
}
await processMessage(message);
}
}Waiting for Multiple Payloads
You can also wait for multiple payloads by using the for await...of syntax.
import { createHook } from "workflow"
export async function collectHookWorkflow() {
'use workflow';
const hook = createHook<{ message: string; done?: boolean }>();
const payloads = [];
for await (const payload of hook) {
payloads.push(payload);
if (payload.done) break;
}
return payloads;
}Related Functions
-
defineHook()- Type-safe hook helper -
resumeHook()- Resume a hook with a payload -
createWebhook()- Higher-level HTTP webhook abstraction