---
title: Publishing Libraries
description: Structure and publish npm packages that export workflow functions for consumers to use with Workflow SDK.
type: guide
summary: Learn how to build, export, and test npm packages that ship workflow and step functions, including package.json exports, re-exporting so the consumer's compiler discovers your workflows, keeping step I/O clean, and integration testing.
---

# Publishing Libraries



<CopyPrompt text="Package these workflow functions as a publishable npm library. Give the package a dedicated workflows entry point (for example `exports[&#x22;./workflows&#x22;]`) that ships the workflow and step source for the consumer's compiler to process. Keep every workflow and step input and output serializable, and read credentials from environment variables inside steps instead of accepting client instances. Document the consumer re-export requirement: consumers create a file in their `workflows/` directory containing `export * from &#x22;<pkg>/workflows&#x22;` so their build discovers and compiles the library's workflow and step files and replay can resolve them after cold starts. Add an integration test that runs a library workflow end to end from a consumer-style setup. Verify the build, that the library's workflows and steps show up as compiled entries, and replay safety." />

import { File, Folder, Files } from "fumadocs-ui/components/files";

<Callout>
  This is an advanced guide for library authors who want to publish reusable workflow functions as npm packages. It assumes familiarity with `"use workflow"`, `"use step"`, and the workflow execution model.
</Callout>

## Package structure

A workflow library follows a standard TypeScript package layout with a dedicated `workflows/` directory. Each workflow file exports one or more workflow functions that consumers can import and pass to `start()`.

<Files>
  <Folder name="my-media-lib" defaultOpen>
    <Folder name="src" defaultOpen>
      <File name="index.ts" />

      <File name="types.ts" />

      <Folder name="workflows" defaultOpen>
        <File name="index.ts" />

        <File name="transcode.ts" />

        <File name="generate-thumbnails.ts" />
      </Folder>

      <Folder name="lib" defaultOpen>
        <File name="api-client.ts" />
      </Folder>
    </Folder>

    <Folder name="test-server" defaultOpen>
      <File name="workflows.ts" />
    </Folder>

    <File name="tsup.config.ts" />

    <File name="package.json" />

    <File name="tsconfig.json" />
  </Folder>
</Files>

Key files:

* **`src/index.ts`**: Package entry point that exports the public API.
* **`src/types.ts`**: Shared TypeScript types.
* **`src/workflows/index.ts`**: Re-exports every workflow so consumers can pull them in under one specifier (see [Entry points and exports](#entry-points-and-exports)).
* **`src/workflows/*.ts`**: One file per workflow function (for example, `transcode.ts` or `generate-thumbnails.ts`).
* **`src/lib/`**: Internal helpers with plain async code that is not marked with `"use workflow"` or `"use step"`.
* **`test-server/workflows.ts`**: Re-export file used by integration tests (see [Test workflow libraries](#test-workflow-libraries)).

### Entry points and exports

Use the `exports` field in `package.json` to expose separate entry points for the main API and the raw workflow functions:

```json
{
  "name": "@acme/media",
  "type": "module",
  "exports": {
    ".": {
      "types": { "import": "./dist/index.d.ts" },
      "import": "./dist/index.js"
    },
    "./workflows": {
      "types": { "import": "./dist/workflows/index.d.ts" },
      "import": "./dist/workflows/index.js"
    }
  },
  "files": ["dist"]
}
```

The main entry point (`@acme/media`) exports types, utilities, and convenience wrappers. The `./workflows` entry point (`@acme/media/workflows`) exports the raw workflow functions that consumers need for the build system.

### Source files

The package entry re-exports workflows alongside any utilities:

```typescript lineNumbers
// src/index.ts
export * from "./types";
export * as workflows from "./workflows";
```

The workflows barrel file re-exports each workflow:

```typescript lineNumbers
// src/workflows/index.ts
export * from "./transcode";
export * from "./generate-thumbnails";
```

### Build configuration

Use a bundler like `tsup` with separate entry points for each export. Mark `workflow` as external so it's resolved from the consumer's project:

```typescript lineNumbers
// tsup.config.ts
import { defineConfig } from "tsup";

export default defineConfig({
  entry: [
    "src/index.ts",
    "src/workflows/index.ts",
  ],
  format: ["esm"],
  dts: true,
  sourcemap: true,
  clean: true,
  external: ["workflow"], // [!code highlight]
});
```

## Re-exporting for compiler discovery

The workflow compiler only transforms files it discovers, and discovery starts from the consumer's `workflows/` directory and follows imports out from there. A library's workflow functions are not on that graph by default, so nothing compiles them and the runtime has no definition to run.

The fix is a **re-export file**. The consumer creates a file in their `workflows/` directory that re-exports the library's workflows, which pulls the library's source onto the discovery graph and gives its entry point an address the runtime can resolve.

### Consumer setup

```typescript lineNumbers
// workflows/media.ts (in the consumer's project)
// Re-export library workflows so the compiler discovers and transforms them
export * from "@acme/media/workflows"; // [!code highlight]
```

This one-line file is all that's needed. The compiler follows the re-export into the package, transforms the workflow and step functions it finds, and registers them under IDs the runtime can resolve.

### Why this is necessary

Without re-exporting, the workflow runtime cannot match a running workflow to its function definition. When a run is replayed after a cold start, the runtime looks up functions by their compiler-assigned IDs. If those functions were never compiled, the IDs don't exist and replay fails.

Point the re-export at the package's dedicated workflows entry point rather than a deep path into `dist/`. Files reachable through the package's `exports` map get an ID of the form `name/subpath@version`; a deep, non-exported file falls back to a path-based ID instead.

<Callout type="info">
  **IDs for code you ship embed your package version.** A step in `@acme/media` version `1.4.0` gets the ID `step//@acme/media/workflows@1.4.0//transcode`, so publishing `1.5.0` renames every workflow and step the package ships.

  That is safe on worlds with deployment pinning, such as Vercel, because runs are pinned to the deployment that started them. A run records its deployment ID and every resume targets that same deployment, so after a consumer upgrades, new runs execute the new version while runs already in flight keep replaying against the old one. Consumers do not need to drain anything before upgrading.

  The re-export file does not change any of this. An ID is derived from where the file lives, not from how it was imported, so a package file keeps its `name@version` ID whether or not a consumer re-exports it.
</Callout>

## Keeping step I/O clean

When you publish a workflow library, every step function's inputs and outputs are recorded in the event log. This has two implications:

### 1. Everything must be serializable

Step inputs and outputs must be serializable. The workflow runtime supports a rich set of types beyond plain JSON, including `Date`, `RegExp`, `Map`, `Set`, `BigInt`, `Uint8Array`, `URL`, `Error`, and class instances that implement [custom class serialization](/docs/foundations/serialization#custom-class-serialization). See the [serialization reference](/docs/foundations/serialization) for the full list of supported types. Do not pass or return:

* Functions or closures
* `WeakRef`, `WeakMap`, or `WeakSet`

If your library works with complex objects that don't implement custom class serialization, pass serializable configuration into steps and reconstruct the objects inside the step body.

{/* @skip-typecheck - good/bad comparison with duplicate function names */}

```typescript lineNumbers
// Good: pass serializable config, construct inside the step
async function callExternalApi(endpoint: string, params: Record<string, string>) {
  "use step";
  const client = createApiClient(process.env.API_KEY!);
  return await client.request(endpoint, params);
}

// Bad: pass a pre-constructed client object
async function callExternalApi(client: ApiClient, params: Record<string, string>) {
  "use step";
  // ApiClient is not serializable, so this will fail on replay
  return await client.request(params);
}
```

See [Serializable Steps](/cookbook/advanced/serializable-steps) for the step-as-factory pattern.

### 2. Credentials

With workflow encryption enabled, credentials passed as step arguments are encrypted in the event log, so either approach is valid:

{/* @skip-typecheck - good/bad comparison with duplicate function names */}

```typescript lineNumbers
// Option A: resolve credentials from environment inside the step
async function fetchData(query: string) {
  "use step";
  const client = createClient(process.env.API_KEY!);
  return await client.fetch(query);
}

// Option B: pass credentials as step arguments (encrypted in the event log)
async function fetchData(apiKey: string, query: string) {
  "use step";
  const client = createClient(apiKey);
  return await client.fetch(query);
}
```

The choice is a matter of library API design preference. Resolving from environment variables keeps the step signature simpler, while passing credentials explicitly makes dependencies visible and can be easier to test.

## Testing workflow libraries

Library authors need integration tests that exercise workflows through the full Workflow SDK runtime, rather than only unit tests of individual functions.

### Test server pattern

Create a minimal test server that re-exports your library's workflows, like a consumer would:

```typescript lineNumbers
// test-server/workflows.ts
export * from "@acme/media/workflows"; // [!code highlight]
```

This test server acts as a stand-in consumer app. Point your test runner at it to exercise the full workflow lifecycle: start, replay, and completion.

### Vitest configuration

Use a dedicated Vitest config for integration tests that run against the Workflow SDK runtime:

```typescript lineNumbers
// vitest.workflowsdk.config.ts
import { defineConfig } from "vitest/config";

export default defineConfig({
  test: {
    include: ["tests/integration/**/*.workflowsdk.test.ts"],
    testTimeout: 120_000, // Workflows may take time to complete
    setupFiles: ["./tests/setup.ts"],
  },
});
```

Run these tests separately from your unit tests:

```bash
# Unit tests (fast, no workflow runtime)
pnpm vitest run tests/unit

# Integration tests (requires workflow runtime)
pnpm vitest run --config vitest.workflowsdk.config.ts
```

### What to test

* **Happy path**: The workflow starts, all steps execute, and the final result is correct.
* **Serialization round-trip**: Inputs and outputs survive the event log.
* **Replay**: Stop and restart a workflow during execution to verify deterministic replay.
* **Error handling**: Step failures produce the expected errors.

## Working with and without Workflow installed

Some libraries need to support consumers who *aren't* using Workflow SDK. The library gains durable behavior when a workflow runtime is present and falls back to plain async execution otherwise.

<Callout type="info">
  Two rules for isomorphic packages:

  1. **Load any runtime reference to the `workflow` package through dynamic `import("workflow")` inside a try/catch.** A static top-level import makes the module fail to load for consumers who haven't installed Workflow.
  2. **Keep the `"use workflow"` and `"use step"` directives in your library source.** When a consumer compiles your code with the Workflow SDK toolchain (via the [re-export pattern](#re-export-for-compiler-discovery) above), the SWC plugin transforms the directives into durable-execution glue. When the directives aren't compiled (plain Node.js, plain tests, or a consumer without the runtime), they are string expression statements and run as no-ops.
</Callout>

### Optional peer dependency

Declare `workflow` as an **optional** peer so consumers without the runtime aren't forced to install it:

```json
{
  "peerDependencies": {
    "workflow": ">=4.0.0"
  },
  "peerDependenciesMeta": {
    "workflow": {
      "optional": true
    }
  }
}
```

### Runtime detection

Wrap a dynamic `import("workflow")` in try/catch. If either the module isn't installed *or* `getStepMetadata()` throws (call site isn't inside a workflow step), fall through to the standalone path.

```typescript lineNumbers
async function getWorkflowStepId(): Promise<string | null> { // [!code highlight]
  try {
    const wf = await import("workflow");
    const { stepId } = wf.getStepMetadata();
    return stepId;
  } catch {
    return null;
  }
}
```

### A concrete use case: replay-safe idempotency keys

A payments utility can use the current workflow step ID as a Stripe idempotency key when available and a fresh universally unique identifier (UUID) otherwise:

```typescript lineNumbers
declare function getWorkflowStepId(): Promise<string | null>; // @setup (defined in the previous block)

export async function processPayment(amount: number, currency: string) {
  const stepId = await getWorkflowStepId();
  const idempotencyKey = stepId ? `payment:${stepId}` : crypto.randomUUID(); // [!code highlight]

  const res = await fetch("https://api.stripe.com/v1/charges", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}`,
      "Idempotency-Key": idempotencyKey, // [!code highlight]
    },
    body: new URLSearchParams({ amount: String(amount), currency }),
  });
  return res.json();
}
```

When called from inside a workflow step, the utility gets a stable idempotency key for that step across retries, so Stripe deduplicates retries. When called from a plain Node.js process, it behaves like any other function and generates a fresh UUID. For more patterns, see [Idempotency](/docs/foundations/idempotency).

### In production

Packages in the wild built on Workflow SDK:

* **[`@mux/ai`](https://github.com/muxinc/ai)**: Reusable video AI workflows (summaries, chapters, content moderation, translation, embeddings) exported with `"use workflow"` / `"use step"` directives. In a standard Node environment the directives are no-ops and the SDK runs as a plain async library; in a Workflow SDK environment the consumer's compiler transforms them into durable, resumable steps with automatic retries and observability. Written up in detail in [*How Mux shipped durable video workflows with their @mux/ai SDK*](https://vercel.com/blog/how-mux-shipped-durable-video-workflows-with-their-mux-ai-sdk) on the Vercel blog.
* **World ID**: Human-in-the-loop "proof of human" primitive for agent workflows. Developers drop a World ID step into any workflow to require a zero-knowledge cryptographic proof that a real, unique human authorized a specific action (deploy approvals, large payments, sensitive data access, etc.). Because it runs as a workflow step, every verification is durable, replay-safe, and viewable inside the run's execution timeline, giving you a provable audit record of which human approved what. Available on npm and announced in [*World ID for agents: Browserbase, Exa, Okta, and Vercel*](https://world.org/blog/announcements/browserbase-exa-okta-world-id-for-agentic-web) on the World blog.

## Checklist

Before publishing a workflow library:

* [ ] `workflow` is listed as an **optional** peer dependency
* [ ] Separate `./workflows` export in `package.json` for the raw workflow functions
* [ ] `workflow` is marked as **external** in your bundler config
* [ ] Documentation tells consumers to re-export from `@your-lib/workflows`
* [ ] Credentials are either resolved from environment variables or passed explicitly (both are safe with encryption enabled)
* [ ] All step I/O uses [supported serializable types](/docs/foundations/serialization)
* [ ] Integration tests use a test server with re-exported workflows
* [ ] Both with-workflow and without-workflow code paths are tested

## Key APIs

* [`"use workflow"`](/docs/foundations/workflows-and-steps#workflow-functions): Declares the orchestrator function.
* [`"use step"`](/docs/foundations/workflows-and-steps#step-functions): Marks functions for durable execution.
* [`start`](/docs/api-reference/workflow-api/start): Starts a workflow run.
* [`getWorkflowMetadata`](/docs/api-reference/workflow/get-workflow-metadata): Provides runtime detection and run ID access.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)

For agent-facing discovery, including API and MCP surfaces, see [/agents.md](/agents.md)