NestJS
Set up your first durable workflow in a NestJS app and learn the core Workflow SDK concepts.
NestJS integration is in beta. Deployment to Vercel is supported via the
workflow-nest build --vercel command. See Deploy to Vercel below.
Create your NestJS project
Start by creating a new NestJS project using the NestJS CLI.
Enter the newly made directory:
Install workflow
Choose your module format
NestJS projects using @workflow/nest can compile as either ESM or CommonJS. Choose the setup that matches your SWC output instead of assuming ESM is required.
ESM (default)
Use this when your NestJS project is configured as an ES module app.
When using ESM with NestJS, local imports must include the .js extension (e.g., import { AppModule } from './app.module.js'). This applies even though your source files are .ts.
CommonJS
Use this when your NestJS project compiles CommonJS via SWC.
distDir should match the directory where NestJS writes compiled .js files. In the default SWC setup, that is dist.
Configure NestJS to use SWC
NestJS supports SWC as an alternative compiler for faster builds. The Workflow SDK uses an SWC plugin to transform workflow files.
Install the required SWC packages:
Ensure your nest-cli.json has SWC as the builder:
Initialize SWC configuration
Run the init command to generate the SWC configuration:
This creates a .swcrc file configured with the Workflow SWC plugin for step-mode transformations.
Add .swcrc to your .gitignore as it contains machine-specific absolute paths that shouldn't be committed.
Update package.json
Add scripts to regenerate the SWC configuration before builds:
Set up IntelliSense for TypeScript (optional)
To enable helpful hints in your IDE, set up the workflow plugin in tsconfig.json:
Import the WorkflowModule
In your app.module.ts, import the WorkflowModule and keep the module format you chose above.
If you chose CommonJS above, keep the CommonJS options here as well:
The .js local import specifiers in this example are the ESM form.
The WorkflowModule handles workflow bundle building and provides HTTP routing for workflow execution at .well-known/workflow/v1/.
Create your first workflow
Create a new file for our first workflow in the src/workflows directory:
Workflow files must be inside the src/ directory so they get compiled with the SWC plugin that enables the start() function to work correctly.
If start() says it received an invalid workflow function, check both of these first:
- The workflow function includes
"use workflow". - The workflow file lives inside
src/so NestJS compiles it with the SWC plugin.
See start-invalid-workflow-function for full examples and fixes.
We'll fill in those functions next, but first review this code:
- We define a workflow function with the directive
"use workflow". Think of the workflow function as the orchestrator of individual steps. - The Workflow SDK's
sleepfunction allows us to suspend execution of the workflow without using up any resources. A sleep can be a few seconds, hours, days, or even months long.
Create your workflow steps
Define the missing functions.
Taking a look at this code:
- Business logic lives inside steps. When a workflow invokes a step, the workflow suspends while the step runs with full Node.js access. The combined handler may execute it inline; queued retries and continuations return through the same flow route.
- If a step throws an error, like in
sendWelcomeEmail, the step will automatically be retried until it succeeds (or hits the step's max retry count). - Steps can throw a
FatalErrorif an error is intentional and should not be retried.
We'll dive deeper into workflows, steps, and other ways to suspend or handle events in Foundations.
Create your controller
To invoke your new workflow, update your controller with a new endpoint:
If you chose CommonJS above, use the same local import style as the rest of your NestJS app here too. The .js extension shown in this example is the ESM form.
This creates a POST endpoint at /signup that will trigger your workflow.
Run in development
To start your development server, run the following command in your terminal:
Once your development server is running, you can trigger your workflow by running this command in the terminal:
Check the NestJS development server logs to see your workflow execute as well as the steps that are being processed.
Additionally, you can use the Workflow SDK CLI or Web UI to inspect your workflow runs and steps in detail.

Deploy to Vercel
Because NestJS is not a Vercel-native framework, the Workflow SDK produces a
Build Output API directory for you. This emits the
workflow queue-consumer function (registered with experimentalTriggers so Vercel's queue can
discover it) alongside your NestJS app as a catch-all function. Without it, workflow runs stay
pending because nothing consumes the queue.
Add a Vercel-specific entry module that default-exports your Nest app's underlying Node handler:
No module change is needed for the in-process build: skipBuild defaults to true when the
VERCEL environment variable is set, because the Build Output already contains the bundles and
the deployed filesystem is read-only.
Set your build command so the Build Output is produced after nest build:
Deploy as usual. workflow-nest build --vercel runs automatically on Vercel (it also detects the
VERCEL environment variable), writing .vercel/output with the consumer function so your runs
execute instead of staying pending.
The app is bundled with esbuild. A package that resolves a dependency at runtime
behind a try/catch — a database driver reached through an ORM, an optional
logger transport — looks like a hard dependency to the bundler, which fails the
build on the first one your app has not installed. NestJS's own optional peers
are handled for you; pass anything else to --external, for example
--external oracledb,mysql2. Native addons (*.node) are not traced into the
deployed function and are reported as a build warning.
Configuration options
The WorkflowModule.forRoot() method accepts optional configuration:
Options can also come from other providers with forRootAsync:
Global prefixes and sub-paths
app.setGlobalPrefix() moves the workflow routes. The SDK has to generate its
queue callback and webhook URLs under the same prefix, or every delivery 404s and
runs stay pending.
WorkflowModule reads the global prefix during startup and adopts it, so this
works with no configuration:
Set basePath explicitly when the prefix is applied outside NestJS, for example
by a reverse proxy that strips it before the request reaches your app. An
explicit basePath wins over the global prefix, and a disagreement between the
two is logged at startup.
For Vercel, pass the same value to the build so the deployed queue-consumer function generates matching URLs:
setGlobalPrefix(prefix, { exclude }) that excludes the workflow routes is
honoured too: they stay at the origin root, and the SDK generates unprefixed
URLs to match. app.enableVersioning() does not move them at all; see
Route versioning.
Request bodies and body parsers
The workflow routes are a byte pipe, in both directions and at whatever size the data happens to be:
- The queue delivers run inputs, step inputs and step outputs in the body of a
POST /.well-known/workflow/v1/flow. Express caps request bodies at 100 KB and NestJS installs that parser by default, so a workflow that passes an array of any size around would get413 request entity too largeon every delivery, with nothing but a retry loop to show for it. - A webhook that verifies a signature over its raw body (Stripe, GitHub, Shopify, Slack) only verifies if the bytes the sender signed arrive unchanged, and a parser that has already turned the request into an object has destroyed them.
WorkflowModule handles both by keeping the application's body parsers away
from .well-known/workflow/v1, and nothing else. On Express, workflow
requests are read straight from the request stream, so they are neither
size-limited nor re-serialized, and your own routes keep the parsers and limits
you configured. No bootstrap configuration is needed, and { rawBody: true } is
not required for signed webhooks.
Set bypassBodyParser: false to opt out and handle parsing yourself.
This stream bypass only applies to uncompressed Express requests. Two cases
fall back to re-serializing the parsed body with JSON.stringify, which does
not preserve whitespace or key order and therefore breaks webhook signature
verification (Stripe, GitHub, Shopify, Slack):
- Fastify. Fastify's content-type parser always consumes the request
stream before the route runs —
WorkflowModulecannot stand it aside the way it does Express's middleware — so the raw bytes are gone by the time the handler sees them. Fastify's body limit is also enforced per instance rather than per route; raise it on the adapter (for examplenew FastifyAdapter({ bodyLimit: 16 * 1024 * 1024 })). - Compressed bodies. A body that arrives with a
content-encodingalways goes through the parser on Express too, because that is what inflates it.
For signed webhooks in either case, create the app with { rawBody: true }
(NestFactory.create(AppModule, new FastifyAdapter(), { rawBody: true }) on
Fastify) so the integration can recover the exact bytes the sender signed.
NestJS keeps them on req.rawBody on both platforms, so no extra plugin is
needed. Without it, the integration logs a one-time warning and falls back to
the lossy JSON.stringify path.
On Vercel the flow and webhook routes are served by their own Build Output functions rather than by your NestJS app, so this only affects self-hosted deployments.
Guards, interceptors, and pipes
The workflow routes are served by a controller inside your application, so a
global guard runs for them too. A guard that rejects unauthenticated requests
rejects every queue delivery and webhook with 403, and runs stop making
progress.
Exempt them with isWorkflowRequest:
The workflow routes authenticate their own callers — queue deliveries are signed and webhook tokens are single-use secrets — so letting them past an application guard exposes nothing.
Interceptors and exception filters are safe to leave in place. The handlers
write through @Res(), so the exact status and body the workflow runtime
produced reach the caller, which is what the queue and third-party webhook
senders key off.
Route versioning
app.enableVersioning() moves every route under a version segment. The workflow
controller is registered as VERSION_NEUTRAL, so it stays at
.well-known/workflow/v1 whichever strategy you enable, and the URLs the SDK
generates keep resolving. A global prefix still applies on top, and is adopted
automatically.
Fastify
@nestjs/platform-fastify is supported alongside @nestjs/platform-express,
with two differences.
Fastify enforces its body limit before any content-type parser runs, and the
limit is per instance rather than per route, so it cannot be scoped to the
workflow routes. Raise it on the adapter; WorkflowModule warns at startup
while it is still at Fastify's 1 MiB default:
Fastify also answers content types it has no parser for with 415 before the
request reaches a controller. Register a catch-all parser if your webhooks send
application/octet-stream or another unparsed media type:
NestJS dependency injection is not available in workflows and steps
Workflows and steps do not run inside your NestJS application. They are compiled
into separate bundles, so the Nest injector, your providers, and anything
built on the request context are out of reach from "use workflow" and
"use step" code.
Concretely, none of these work inside a step:
- injecting a provider, or resolving one with
app.get(MyService) @Injectable()classes reached through a module-level reference to the app- request-scoped providers, and
AsyncLocalStoragecontext such asnestjs-cls - guards, interceptors, pipes, and filters
- the Nest
Logger
Two mechanics cause this, and neither has a workaround:
- A step's bundle gets its own copy of any application file it imports.
Module-level state is therefore duplicated, and a class imported into a step
is a different class object from the one your module registered. Nest uses the
class itself as the injection token, so
app.get(MyService)from a step raisesUnknownElementExceptioneven when it can reach the app. - On Vercel, workflows and steps run in the queue-consumer function, a separate function from the one serving your NestJS app. There is no shared process to reach into.
Write steps as plain functions over their arguments, and keep the wiring in your controllers and providers:
Configuration a step needs should come from the environment rather than
ConfigService, and shared logic should live in plain modules that a step can
import without pulling in @nestjs/common.
Importing a file that uses @nestjs/common into a step is supported and builds
correctly, it simply gives you a class with no injected dependencies. Prefer
plain functions so the intent is clear.
Production checklist
- Run
workflow-nest buildin your build step and setskipBuild: true, or leaveskipBuildunset so the bundles are built during startup. WithskipBuildset and no bundles present, startup fails with an explicit error rather than serving broken workflow routes. - Exempt the workflow routes from any global guard with
isWorkflowRequest, or every queue delivery is rejected with403. - Set
basePath(or rely on the adopted global prefix) so generated URLs match the routes NestJS serves. - Set
manageWorldLifecycle: truefor a self-hosted World, and callapp.enableShutdownHooks()so the World is closed on a signal. - On Fastify, raise the adapter's
bodyLimitabove the data your workflows pass between steps. - Install exactly one copy of
@nestjs/core. With two, NestJS hands@workflow/nestneither the global prefix nor the HTTP adapter, which silently disables prefix handling and the body-parser bypass; a warning is logged at startup when this happens. skipBuilddefaults totruewhen theVERCELenvironment variable is set, so no Vercel-specific branch is needed in your module configuration.
Troubleshooting
start() says it received an invalid workflow function
If you see this error:
Check both of these first:
- The workflow function includes
"use workflow". - Your NestJS app imports and registers the
WorkflowModule.
See start-invalid-workflow-function for full examples and fixes.
Next steps
- Learn more about the Foundations.
- Check Errors if you encounter issues.
- Explore the API Reference.