惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

F
Fortinet All Blogs
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
有赞技术团队
有赞技术团队
www.infosecurity-magazine.com
www.infosecurity-magazine.com
大猫的无限游戏
大猫的无限游戏
爱范儿
爱范儿
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
Threatpost
V
Visual Studio Blog
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - Franky
人人都是产品经理
人人都是产品经理
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
The Cloudflare Blog
N
News and Events Feed by Topic
L
Lohrmann on Cybersecurity
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
酷 壳 – CoolShell
酷 壳 – CoolShell
V
V2EX
AWS News Blog
AWS News Blog
S
SegmentFault 最新的问题
T
Tailwind CSS Blog
Hugging Face - Blog
Hugging Face - Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Spread Privacy
Spread Privacy
J
Java Code Geeks
博客园 - 聂微东
T
Tor Project blog
宝玉的分享
宝玉的分享
博客园 - 叶小钗
Webroot Blog
Webroot Blog
博客园 - 【当耐特】
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
H
Heimdal Security Blog
Y
Y Combinator Blog
T
The Blog of Author Tim Ferriss
MongoDB | Blog
MongoDB | Blog
I
InfoQ
Security Latest
Security Latest
Martin Fowler
Martin Fowler
Hacker News: Ask HN
Hacker News: Ask HN
P
Privacy International News Feed
C
CERT Recently Published Vulnerability Notes
Latest news
Latest news
雷峰网
雷峰网
D
Darknet – Hacking Tools, Hacker News & Cyber Security
C
Cisco Blogs
H
Help Net Security
L
LINUX DO - 最新话题
L
LINUX DO - 热门话题

Workflow SDK Documentation

Patterns for Defining Tools Human-in-the-Loop Building Durable AI Agents Queueing User Messages Resumable Streams Sleep, Suspense, and Scheduling Streaming Updates from Tools API Reference Workflow Globals Changelog Resilient run start Cookbook Building a World Deploying Astro Express Fastify Hono Getting Started NestJS Next.js Nitro Nuxt Python SvelteKit Vite corrupted-event-log fetch-in-workflow hook-conflict Errors node-js-module-in-workflow serialization-failed start-invalid-workflow-function step-not-registered timeout-in-workflow webhook-invalid-respond-with-value webhook-response-not-sent workflow-not-registered Errors & Retrying Hooks & Webhooks Idempotency Foundations Serialization Streaming Versioning Workflows and Steps How the Directives Work Encryption Event Sourcing Framework Integrations Understanding Directives Migration Guides Migrating from AWS Step Functions Migrating from Inngest Migrating from Temporal Observability Testing Server-Based Testing createHook createWebhook defineHook FatalError fetch getStepMetadata getWorkflowMetadata getWritable workflow RetryableError sleep @workflow/vitest DurableAgent @workflow/ai WorkflowChatTransport getHookByToken getRun getWorld workflow/api resumeHook resumeWebhook Chat Session Modeling runtime-decryption-failed Upgrading Workflows abort-signal-timeout-in-workflow Cancellation How Cancellation Works Internal Serializable AbortController and AbortSignal Eager Processing of Steps & Incremental Event Replay TanStack Start Agent Cancellation Sequential & Parallel Execution Workflow Composition Local World | Workflow SDK Postgres World | Workflow SDK Vercel World | Workflow SDK Migrating from trigger.dev Secure Credential Handling Local World | Workflow SDK Postgres World | Workflow SDK Vercel World | Workflow SDK
Starting Workflows
2026-05-31 · via Workflow SDK Documentation

Trigger workflow execution with the start() function and track progress with Run objects.

Once you've defined your workflow functions, you need to trigger them to begin execution. This is done using the start() function from workflow/api, which enqueues a new workflow run and returns a Run object that you can use to track its progress.

The start() function is used to programmatically trigger workflow executions from runtime contexts like API routes, Server Actions, or any server-side code.

import { start } from "workflow/api";
import { handleUserSignup } from "./workflows/user-signup";

export async function POST(request: Request) {
  const { email } = await request.json();

  // Start the workflow
  const run = await start(handleUserSignup, [email]); 

  return Response.json({
    message: "Workflow started",
    runId: run.runId
  });
}

Key Points:

  • start() returns immediately after enqueuing the workflow - it doesn't wait for completion
  • The first argument is your workflow function
  • The second argument is an array of arguments to pass to the workflow (optional if the workflow takes no arguments)
  • All arguments must be serializable

Learn more: start() API Reference

When you call start(), it returns a Run object that provides access to the workflow's status and results.

import { start } from "workflow/api";
import { processOrder } from "./workflows/process-order";

const run = await start(processOrder, [/* orderId */]);

// The run object has properties you can await
console.log("Run ID:", run.runId);

// Check the workflow status
const status = await run.status; // "running" | "completed" | "failed"

// Get the workflow's return value (blocks until completion)
const result = await run.returnValue;

Key Properties:

  • runId - Unique identifier for this workflow run
  • status - Current status of the workflow (async)
  • returnValue - The value returned by the workflow function (async, blocks until completion)
  • readable - ReadableStream for streaming updates from the workflow

Most Run properties are async getters that return promises. You need to await them to get their values. For a complete list of properties and methods, see the API reference below.

Learn more: Run API Reference

Fire and Forget

The most common pattern is to start a workflow and immediately return, letting it execute in the background:

import { start } from "workflow/api";
import { sendNotifications } from "./workflows/notifications";

export async function POST(request: Request) {
  // Start workflow and don't wait for it
  const run = await start(sendNotifications, [userId]);

  // Return immediately
  return Response.json({
    message: "Notifications queued",
    runId: run.runId
  });
}

Wait for Completion

If you need to wait for the workflow to complete before responding:

import { start } from "workflow/api";
import { generateReport } from "./workflows/reports";

export async function POST(request: Request) {
  const run = await start(generateReport, [reportId]);

  // Wait for the workflow to complete
  const report = await run.returnValue; 

  return Response.json({ report });
}

Be cautious when waiting for returnValue - if your workflow takes a long time, your API route may timeout.

Stream Updates to Client

Stream real-time updates from your workflow as it executes, without waiting for completion:

import { start } from "workflow/api";
import { generateAIContent } from "./workflows/ai-generation";

export async function POST(request: Request) {
  const { prompt } = await request.json();

  // Start the workflow
  const run = await start(generateAIContent, [prompt]);

  // Get the readable stream (can also use run.readable as shorthand)
  const stream = run.getReadable(); 

  // Return the stream immediately
  return new Response(stream, {
    headers: {
      "Content-Type": "application/octet-stream",
    },
  });
}

Your workflow can obtain a writable stream using getWritable():

import { getWritable } from "workflow";

export async function generateAIContent(prompt: string) {
  "use workflow";

  const writable = getWritable(); 

  await streamContentToClient(writable, prompt);

  return { status: "complete" };
}

async function streamContentToClient(
  writable: WritableStream,
  prompt: string
) {
  "use step";

  const writer = writable.getWriter();

  // Stream updates as they become available
  for (let i = 0; i < 10; i++) {
    const chunk = new TextEncoder().encode(`Update ${i}\n`);
    await writer.write(chunk);
  }

  writer.releaseLock();
}

Streams are particularly useful for AI workflows where you want to show progress to users in real-time, or for long-running processes that produce intermediate results.

Learn more: Streaming in Workflows

Check Status Later

You can retrieve a workflow run later using its runId with getRun():

import { getRun } from "workflow/api";

export async function GET(request: Request) {
  const url = new URL(request.url);
  const runId = url.searchParams.get("runId");

  // Retrieve the existing run
  const run = getRun(runId); 

  // Check its status
  const status = await run.status;

  if (status === "completed") {
    const result = await run.returnValue;
    return Response.json({ result });
  }

  return Response.json({ status });
}

Now that you understand how to start workflows and track their execution: