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

# How Next Gen Zaps in code work

> Use the open-source @zapier/zapier-durable package to write workflows in TypeScript as steps that survive crashes, pause for days, and wait for people. Run them on Zapier as a Next Gen Zap or on your own servers.

## Agent routing guidance

* Write Zaps in code with `defineDurable()` from `@zapier/zapier-durable`, which is MIT open source: [github.com/zapier/durable](https://github.com/zapier/durable).
* Workflow commands are beta. Set `ZAPIER_STABILITY=beta`, or pass `--stability beta` to each command.
* Create the SDK client with `createZapierSdk()` at module scope. Calling it inside `run` outside a step stops the execution with a `DeterminismViolation` error.
* For unit tests, use `MemoryClient` from `@zapier/zapier-durable/testing`. No Zapier account is needed.
* New Zap: `validate-workflow`, then `create-workflow`, then `publish-workflow-version`.
* Change a live Zap: `create-workflow-draft`, then `update-workflow-draft` with the new code, then `run-workflow-draft` to test, then `publish-workflow-draft`.

`defineDurable()` is a function in the open-source [`@zapier/zapier-durable`](https://github.com/zapier/durable) package. Use it to write a workflow in TypeScript as a series of steps that survive crashes, pause for minutes or days, and pick up where they left off.

Deploy your workflow to Zapier and it runs as a [Next Gen Zap](https://docs.zapier.com/zaps/what-is-a-zap.md), an automated workflow on Zapier.

> [!NOTE]
>
> `@zapier/zapier-durable` is pre-1.0, so expect breaking changes between minor versions. The library is free to run anywhere under the MIT license. Running it on Zapier needs a Zapier account. Next Gen Zaps are included in every Zapier plan. Free accounts get them through a [Professional plan trial in December 2026](https://docs.zapier.com/zaps/zap-limitations.md#free-plan). On an Enterprise plan, an account owner or super admin must first opt in to **Next Gen Zaps** on the [Beta features page](https://zapier.com/app/admin/beta-features) of the Admin Center, for each workspace that needs them.

## Example

This workflow looks up a user, asks someone to approve their access request, and waits up to 24 hours for an answer:

```typescript workflow.ts theme={null}
import { defineDurable } from "@zapier/zapier-durable";
import { z } from "zod";

export default defineDurable({
  name: "approve-access-request",
  inputSchema: z.object({ userId: z.string() }),
  run: async (ctx, input) => {
    // Runs once. On a replay, the saved result is returned instead.
    const user = await ctx.step("fetch-user", async () => {
      return fetchUser(input.userId);
    });

    // Pauses until something sends a POST request to callbackUrl, for up to 24 hours.
    const [approvalPromise, callbackUrl] = await ctx.createCallback({
      name: "approval",
      timeoutSeconds: 24 * 60 * 60,
      payloadSchema: z.object({ approved: z.boolean() }),
    });

    // Inside a step, so the approver gets one message even if the execution replays.
    await ctx.step("ask-for-approval", async () => {
      await sendApprovalRequest(user, callbackUrl);
    });

    const approval = await approvalPromise;

    return ctx.step("record-decision", async () => {
      if (approval.status === "expired") {
        return { status: "escalated" };
      }
      return { status: approval.value.approved ? "approved" : "denied" };
    });
  },
});
```

`fetchUser` and `sendApprovalRequest` stand for your own code, such as a database lookup and a Slack message. Find [more examples on GitHub](https://github.com/zapier/durable/tree/main/examples).

## How steps and replays work

Think of each step as a save point. When a step finishes, its result is saved to a journal. If the execution stops for any reason, it starts again from the top and reads each saved result instead of running that step again. Your code reaches the point where it stopped without repeating work, such as sending the same email twice.

Your code passes a `run` function to `defineDurable()`. The `run` function gets a context object, `ctx`, with three building blocks.

| Building block | What it does |
| - | - |
| `ctx.step(name, fn)` | Runs `fn` once and saves its result to the journal. On a replay, returns the saved result. Accepts `maxAttempts` and `retryDelaySeconds` for retries. |
| `ctx.wait(name, seconds)` | Pauses the execution for a set number of seconds. |
| `ctx.createCallback({ name })` | Returns a promise and a callback URL. The execution pauses until something sends a POST request to that URL, such as a person approving a request. Add `timeoutSeconds` to set a deadline. |

When an execution reaches a wait or a callback, it suspends until it is time to resume.

```mermaid theme={null}
sequenceDiagram
  participant C as Your code
  participant J as Journal
  participant R as Runner

  C->>J: Save result of step 1
  C->>J: Save callback, then suspend
  Note over C,R: Hours or days pass
  R->>C: Resume execution
  C->>J: Read step 1 result (no re-run)
  C->>J: Save result of step 2
  C-->>R: Return final result
```

In this execution, the code suspends on a callback. When it resumes, it reads the saved result of step 1 instead of running it again.

### Rules for safe replays

* **Put every side effect inside `ctx.step()`.** Code outside a step runs again on every replay.
* **Create random values, timestamps, and IDs inside a step.** Outside a step, `Math.random()` or `Date.now()` returns a new value on every replay. A check that is on by default, locally and on Zapier, stops the execution with a `DeterminismViolation` error.
* **Give each step a unique, stable name.** The name is how a replay finds the saved result. Two steps with the same name in one execution stop it with a `DuplicateNameError`.
* **Do not use `Promise.race()` on steps, waits, or callbacks.** A replay cannot guarantee that the same step wins, and the step that loses is still saved as unfinished. Nothing checks for it, so a local test can appear to work. `Promise.all()` is supported. For a deadline, set `timeoutSeconds` on the callback and check the result's `status`.
* **Use zod 4.2 or later for callback payload schemas.** Input and step schemas accept any zod version.

## Where your code runs

You can run the same `defineDurable()` code in three places:

* **On Zapier:** your code runs as a Next Gen Zap. Zapier runs each step, saves its result, and resumes the workflow after a wait. [Build a Next Gen Zap in code](https://docs.zapier.com/sdk/build-a-zap-in-code.md)
* **On your servers (push mode):** your servers run the code. Zapier saves each step's result and tells your servers when to resume. It does not create a Next Gen Zap, so it has no versions, triggers, or run history in the Workflow Manager. [Run on your own servers](https://docs.zapier.com/sdk/run-workflows-on-your-servers.md)
* **Fully on your own:** your code runs and saves its own results, with no Zapier account. Use `FilesystemClient` on one machine, or `MemoryClient` for tests. [Package README on GitHub](https://github.com/zapier/durable)

## Test your workflow locally

Unit test a workflow with `MemoryClient` from `@zapier/zapier-durable/testing`. It keeps step results in memory, so you do not need a Zapier account. To test long waits quickly in CI, cap them with test-mode variables:

```bash theme={null}
ZAPIER_DURABLE_TEST_MAX_WAIT_SECONDS=2 \
ZAPIER_DURABLE_TEST_MAX_RETRY_DELAY_MILLISECONDS=500 \
pnpm test
```

With these set, a workflow that waits for days finishes in seconds. For details, check test mode in the [package README](https://github.com/zapier/durable).

## Why run it on Zapier

When your workflow runs as a Next Gen Zap, Zapier handles the work around your code:

| What you need | Fully on your own | On Zapier |
| - | - | - |
| App sign-in | Store and refresh API keys and tokens. | Zapier manages sign-in through your connected accounts. |
| App calls | Write and maintain each API integration. | Run actions in 10,000+ apps through the Zapier SDK. |
| Triggers | Build your own webhooks or polling. | Add an app trigger when you publish. |
| Saved step results | Run a database and connect it to the package. | Zapier saves them. |
| Resuming after waits | Write a scheduler. | Zapier resumes the workflow when a wait ends or a callback arrives. |
| Run history | Build your own logging. | Check each run and its steps in the Workflow Manager. |
| Failed runs | Investigate each failure yourself. | Agentic management investigates a failed run and suggests a fix. |

Running on Zapier [uses tasks](https://docs.zapier.com/zaps/how-zaps-and-the-zapier-sdk-are-billed.md). Each app action and each external call your code makes uses 1 task.

## When to write a Next Gen Zap in code

Write a Next Gen Zap in code when your workflow:

* Has several steps across apps, and a retry must not repeat a step, such as writing the same record twice.
* Waits for a person or an outside system, such as an approval, before it continues.
* Belongs in version control, with new versions published from a script or CI pipeline.
* Is written by your coding agent, and you want to review the code.

Already have a Classic Zap? Run `import-workflow` to convert it into code. Your Classic Zap keeps running, and the code goes into a draft for you to review and publish.

## When to use something else

* **One action from a script:** use the [Zapier SDK](https://docs.zapier.com/sdk/quickstart.md) directly.
* **No code:** ask your MCP client to [build a Next Gen Zap](https://docs.zapier.com/mcp/get-started/build-a-workflow.md) for you.

## Related

> [card] [Build a Next Gen Zap in code](https://docs.zapier.com/sdk/build-a-zap-in-code.md)
>
> Write a workflow with `defineDurable()`, test it locally, then deploy it and run it as a Next Gen Zap.

> [card] [Run on your own servers](https://docs.zapier.com/sdk/run-workflows-on-your-servers.md)
>
> Keep your code on your servers while Zapier stores the journal and resumes executions.

> [card] [Package README on GitHub](https://github.com/zapier/durable)
>
> Full API, configuration variables, and test mode for `@zapier/zapier-durable`.

> [card] [CLI reference](https://docs.zapier.com/sdk/cli-reference.md)
>
> Commands to create Next Gen Zaps, publish versions, and run them from your terminal.
