> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/vercel/workflow/llms.txt
> Use this file to discover all available pages before exploring further.

# Welcome to Workflow DevKit

> Build durable, resilient, and observable workflows in JavaScript with ease. Add reliability to async operations, AI agents, and complex business logic.

<div align="center">
  <img src="https://useworkflow.dev/workflow-circle-symbol-light.svg" alt="Workflow DevKit" width="128" height="128" />
</div>

# Welcome to Workflow DevKit

Workflow DevKit lets you easily add **durability**, **reliability**, and **observability** to async JavaScript. Build apps and AI agents that can suspend, resume, and maintain state with ease.

<Note>
  Built by engineers at [Vercel](https://vercel.com), Workflow DevKit is designed to integrate seamlessly with modern JavaScript frameworks like Next.js, SvelteKit, Nuxt, and more.
</Note>

## Why Workflow DevKit?

Building reliable async operations in JavaScript is hard. Workflows can fail midway, external APIs can timeout, and maintaining state across retries is complex. Workflow DevKit solves these problems by providing:

<CardGroup cols={2}>
  <Card title="Durability" icon="shield-check">
    Workflows automatically persist their state. If your server crashes or restarts, workflows resume exactly where they left off.
  </Card>

  <Card title="Automatic Retries" icon="rotate">
    Failed steps are automatically retried with configurable backoff strategies. No manual retry logic needed.
  </Card>

  <Card title="Observability" icon="chart-line">
    Built-in OpenTelemetry support gives you deep insights into workflow execution, performance, and errors.
  </Card>

  <Card title="Type Safety" icon="code">
    Full TypeScript support with intelligent type inference. Catch errors at compile time, not runtime.
  </Card>
</CardGroup>

## Perfect For

Workflow DevKit excels at handling complex async operations:

* **AI Agents**: Build durable AI agents that can pause for external tool calls, wait for user input, or handle long-running LLM operations
* **User Onboarding**: Create multi-step signup flows with emails, webhooks, and delayed follow-ups
* **Data Processing**: Orchestrate ETL pipelines, batch jobs, and multi-stage transformations
* **API Orchestration**: Coordinate calls to multiple external services with proper error handling
* **Human-in-the-Loop**: Build workflows that pause for manual approval or user action

## How It Works

Workflow DevKit uses two simple directives to mark your functions:

<CodeGroup>
  ```typescript Simple Workflow theme={null}
  export async function handleUserSignup(email: string) {
    'use workflow';

    const user = await createUser(email);
    await sendWelcomeEmail(user);
    await sleep('5s');
    await sendFollowUpEmail(user);

    return { userId: user.id, status: 'onboarded' };
  }

  async function createUser(email: string) {
    'use step';
    return { id: crypto.randomUUID(), email };
  }

  async function sendWelcomeEmail(user: { id: string; email: string }) {
    'use step';
    console.log(`Sending welcome email to ${user.email}`);
  }

  async function sendFollowUpEmail(user: { id: string; email: string }) {
    'use step';
    console.log(`Sending follow-up email to ${user.email}`);
  }
  ```

  ```typescript AI Agent theme={null}
  import { generateText } from 'ai';
  import { FatalError } from 'workflow';

  async function getWeather(city: string) {
    'use step';
    // External API call - automatically retried on failure
    const response = await fetch(`https://api.weather.com/${city}`);
    return response.json();
  }

  export async function weatherAgent(prompt: string) {
    'use workflow';

    const { text } = await generateText({
      model: 'anthropic/claude-4-opus',
      prompt,
      tools: {
        getWeather: {
          description: 'Get weather for a city',
          execute: getWeather,
        },
      },
    });

    return text;
  }
  ```

  ```typescript Error Handling theme={null}
  import { FatalError, RetryableError } from 'workflow';

  async function processPayment(amount: number) {
    'use step';

    try {
      const result = await stripe.charges.create({ amount });
      return result;
    } catch (error) {
      if (error.type === 'card_error') {
        // Don't retry payment errors
        throw new FatalError('Payment failed: ' + error.message);
      }
      // Retry network errors after 30 seconds
      throw new RetryableError('Payment service unavailable', {
        retryAfter: '30s'
      });
    }
  }

  export async function checkout(items: Item[]) {
    'use workflow';

    const total = items.reduce((sum, item) => sum + item.price, 0);
    const payment = await processPayment(total);
    await sendReceipt(payment);

    return payment;
  }
  ```
</CodeGroup>

## Key Features

### Durable State Management

Workflows persist their execution state after each step. If your application crashes or restarts, workflows resume from the last completed step:

```typescript theme={null}
export async function dataProcessing(fileUrl: string) {
  'use workflow';

  const file = await downloadFile(fileUrl);      // Step 1: Persisted
  const parsed = await parseFile(file);          // Step 2: Persisted
  const validated = await validateData(parsed);  // Step 3: Persisted
  await uploadResults(validated);                // Step 4: Persisted

  return { status: 'complete', records: validated.length };
}
```

If the workflow fails at Step 3, it will resume from Step 3 without re-executing Steps 1 and 2.

### Smart Fetch Hoisting

HTTP requests are automatically extracted and made durable. No need to wrap every fetch in a step:

```typescript theme={null}
export async function fetchData() {
  'use workflow';

  // This fetch is automatically hoisted and retried
  const response = await fetch('https://api.example.com/data');
  const data = await response.json();

  return data;
}
```

### Built-in Utilities

Workflow DevKit provides powerful utilities for common patterns:

* **`sleep(duration)`**: Pause execution for a specific duration
* **`createHook()`**: Create resumable hooks for callbacks
* **`createWebhook()`**: Generate webhook URLs for external services
* **`getWorkflowMetadata()`**: Access workflow context and run information
* **`getStepMetadata()`**: Get step execution details and retry counts

### Webhooks and Hooks

Pause workflows and resume them via webhooks or custom callbacks:

```typescript theme={null}
import { createWebhook, sleep } from 'workflow';

export async function approvalFlow(requestId: string) {
  'use workflow';

  await notifyApprover(requestId);

  const webhook = createWebhook();
  await sendApprovalEmail(requestId, webhook.url);

  // Wait for webhook to be called or timeout after 24 hours
  const approval = await Promise.race([
    webhook,
    sleep('24h').then(() => ({ approved: false, reason: 'timeout' }))
  ]);

  if (approval.approved) {
    await processApprovedRequest(requestId);
  } else {
    await handleRejection(requestId, approval.reason);
  }
}
```

## Framework Support

Workflow DevKit integrates seamlessly with popular JavaScript frameworks:

<CardGroup cols={3}>
  <Card title="Next.js" icon="react" href="/frameworks/nextjs">
    Full App Router and Pages Router support
  </Card>

  <Card title="SvelteKit" icon="code" href="/frameworks/sveltekit">
    Native SvelteKit integration
  </Card>

  <Card title="Nuxt" icon="n" href="/frameworks/nuxt">
    Nuxt 3 with Nitro support
  </Card>

  <Card title="Astro" icon="rocket" href="/frameworks/astro">
    Server-side workflow execution
  </Card>

  <Card title="NestJS" icon="code" href="/frameworks/nestjs">
    Enterprise-ready workflows
  </Card>

  <Card title="Vite" icon="bolt" href="/frameworks/vite">
    Universal Vite plugin
  </Card>
</CardGroup>

## Ready to Get Started?

Jump into the quickstart guide to build your first workflow in under 5 minutes:

<Card title="Quickstart Guide" icon="rocket" href="/quickstart">
  Build and deploy your first durable workflow
</Card>

## Community & Support

<CardGroup cols={2}>
  <Card title="GitHub Discussions" icon="github" href="https://github.com/vercel/workflow/discussions">
    Ask questions and share your projects
  </Card>

  <Card title="Report Issues" icon="bug" href="https://github.com/vercel/workflow/issues">
    Found a bug? Let us know
  </Card>

  <Card title="API Reference" icon="book" href="/api">
    Complete API documentation
  </Card>

  <Card title="Examples" icon="code" href="/examples">
    Real-world workflow examples
  </Card>
</CardGroup>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.