What are Nx continuous tasks and what problem do they solve?
A continuous task is an Nx target that is expected to run indefinitely, such as a dev server, an API in watch mode, or a local queue consumer. You mark it with continuous: true in the target configuration. Other tasks can then depend on it without waiting for it to exit, because by definition it never does.
That distinction matters because of how a normal dependsOn entry works. Nx treats a dependency as a prerequisite that must finish successfully before the dependent task starts. If your e2e target lists serve as a regular dependency, Nx starts the server and waits for it to complete. A server only completes when it crashes or is killed, so the e2e task never begins and the pipeline hangs until a timeout ends it.
Before continuous tasks, teams used several workarounds:
- Backgrounded shell commands: start the server with
&, sleep for a few seconds, then run the tests. - Wrapper scripts: start the API, poll a port, run the suite, then kill the server.
- Test-runner
webServerhooks: let the e2e framework launch and stop the backend itself.
Each of these moves process management outside Nx, and each fails in its own way. When a test fails or someone presses Ctrl+C, the cleanup step can be skipped, leaving orphaned servers holding the port. A fixed sleep that works on a fast laptop falls short on a loaded CI runner. Nx also has no view of these processes, so it can't schedule, reuse, or tear them down consistently.
This guide is for backend and platform engineers whose e2e suites need a running API.
Who should use Nx continuous tasks?
Continuous tasks fit teams that already run their tests through Nx and whose e2e suites need one or more long-running processes from the same workspace. Typical cases:
- Backend engineers in an Nx monorepo whose API e2e project calls a server built from source in the same repository. Declaring
api:serveas a dependency replaces the "start the API in another terminal first" step. - Frontend engineers whose browser e2e tests need both the web app and its API running at once. One
dependsOnlist starts both. - Platform and CI owners who maintain wrapper scripts that start servers, poll ports and kill processes. Moving that lifecycle into Nx removes a script that every pipeline has to keep in sync.
- Teams using
nx affectedin CI who want backends started only when an affected e2e target actually needs them.
They fit less well if your tests are mostly run directly by a test runner outside Nx, or if the dependency is stateful infrastructure such as a database or message broker that you don't build from source. The section on when to avoid continuous tasks covers those cases.
How does it work? Nx continuous tasks during an e2e run
Marking a target "continuous": true changes how Nx treats its exit. A normal task is finished when its process exits, and anything depending on it waits for that exit. A continuous task is expected never to exit, so Nx starts it and immediately counts it as satisfied for scheduling. The process keeps running while the tasks that depend on it execute.
Take a web-e2e project whose e2e target lists both web:serve and api:serve in dependsOn, with both serve targets marked continuous. Running web-e2e:e2e goes through three phases:
| Phase | api:serve |
web:serve |
web-e2e:e2e |
|---|---|---|---|
| 1. Start | spawned | spawned | waiting |
| 2. Run | running | running | executing tests |
| 3. Teardown | signalled, exits | signalled, exits | finished (pass or fail) |
In phase 1, Nx first runs any ordinary dependencies the servers have, such as a build target, to completion. It then spawns both servers. They have no dependency on each other, so their start order isn't guaranteed. In phase 2, the e2e runner executes against whatever those processes are doing. In phase 3, once the e2e task exits, Nx sends termination signals to the continuous tasks it started. Nothing is left orphaned on your machine or a CI runner.
Nx does not check readiness. "Started" only means the process was spawned. It does not mean the API has bound its port, connected to its database, or finished migrations. If your tests make their first request during that window, they fail even though the configuration is correct. Readiness is your responsibility, and a later section covers how to handle it.
PHASE 1: START
┌────────────────┐ ┌────────────────┐
│ api:build │ │ web:build │ ordinary deps (if any)
└───────┬────────┘ └───────┬────────┘ run until they exit
│ │
▼ ▼
┌────────────────┐ ┌────────────────┐ spawned, not awaited;
│ api:serve │ │ web:serve │ no start order between
│ (continuous) │ │ (continuous) │ the two servers
└───────┬────────┘ └───────┬────────┘
│ spawned != ready │ Nx does NOT check readiness
└──────────┬───────────┘
▼ PHASE 2: RUN
┌───────────────────┐
│ web-e2e:e2e │◄── both servers keep running throughout
│ tests execute │
└─────────┬─────────┘
│ exits (pass or fail)
▼ PHASE 3: TEARDOWN
┌─────────────────────────────────────────┐
│ Nx sends termination signals to the │
│ continuous tasks it started: │
│ api:serve and web:serve both exit │
└─────────────────────────────────────────┘
nothing left orphaned locally or on CI
Lifecycle of nx run web-e2e:e2e: ordinary build dependencies run to completion, both continuous serve targets are spawned without a readiness check, the e2e tests run while the servers stay up, and Nx signals both servers to exit when the e2e task finishes.
How do you configure serve as continuous and wire it into e2e dependsOn?
Start with the server. In apps/api/project.json, add "continuous": true to the serve target. This tells Nx the task never exits by design. Nx starts it, keeps it running while dependent tasks execute, and stops it when they finish. It does not wait for the server to exit before moving on.
Same-project and cross-project forms
If the e2e target lives in the same project as the server, "dependsOn": ["serve"] is enough. Most workspaces keep tests in a separate project, though, so api-e2e uses the cross-project form: "dependsOn": ["api:serve"]. Nx resolves the reference across the project graph. Running nx e2e api-e2e then starts the API first, without a wrapper script.
A frontend e2e project usually needs two processes. List both: "dependsOn": ["web:serve", "api:serve"]. Nx starts the two continuous tasks in parallel. You get one command and one teardown, and no orphaned servers.
Use a dedicated configuration
Don't point tests at the plain serve target. That runs the hot-reloading dev server with your dev database and secrets. A file save mid-run can restart it, and tests can write junk into data you care about.
Instead, add a serve:e2e configuration to the serve target. Give it its own test database URL, a fixed port that doesn't collide with dev, and its own env file. The exact option names depend on your executor. Then reference it explicitly: "dependsOn": ["api:serve:e2e"].
After the run, confirm Nx released the port. lsof -i :<port> or ss -ltnp should show nothing still listening. If a process is still listening, teardown failed, and the next run will hit a port conflict.
{
"apps/api/project.json": {
"targets": {
"serve": {
"continuous": true,
"executor": "nx:run-commands",
"options": {
"command": "node --watch dist/apps/api/main.js",
"envFile": "apps/api/.env.development"
},
"configurations": {
"e2e": {
"command": "node dist/apps/api/main.js",
"envFile": "apps/api/.env.e2e",
"env": {
"PORT": "3334",
"DATABASE_URL": "postgres://e2e_user:e2e_pass@localhost:5433/api_e2e"
}
}
}
}
}
},
"apps/api-e2e/project.json": {
"targets": {
"e2e": {
"dependsOn": ["api:serve:e2e"]
}
}
},
"apps/web-e2e/project.json": {
"targets": {
"e2e": {
"dependsOn": ["web:serve", "api:serve:e2e"]
}
}
}
}
Fragments of three project.json files, keyed by path: a continuous api serve target with an e2e configuration, plus api-e2e and web-e2e depending on it. Options shown are for nx:run-commands; other executors use different names.
How do you make sure the server is ready before tests run?
Nx starts a continuous task and then moves on. It does not know when your server has bound its port, run migrations, or warmed its connection pool. As soon as serve is launched, the e2e target can begin. The gap between "process started" and "server accepting requests" is your responsibility to close.
Expose a dedicated health endpoint, such as GET /health, that returns 200 only after the app has finished initializing. Readiness checks should target that endpoint. A fixed sleep is not a substitute. A 5-second delay that works on your laptop is a guess about startup time, and startup time varies with CPU contention, cold dependency caches, and container scheduling. Shared or smaller CI runners are slower, so the guess fails there first. The resulting flakiness is intermittent and hard to reproduce locally.
Three patterns
- Polling in global setup. Before any test runs, request the health URL in a loop. A typical setup waits about 250 ms between attempts, treats connection errors as "not ready yet," and stops on the first 200. If the total wait passes a hard limit, for example 60 seconds, fail with a clear message. The setup should never hang indefinitely.
- Retry on the first request. Wrap the suite's first API call in a bounded retry with backoff. This works when you can't add a global setup hook. It mixes readiness handling with test logic, though, so prefer global setup where you can.
- The runner's wait-for-URL option. Some test runners can wait on a URL before starting tests. Point that option at the health endpoint. Don't also let the runner start the server, or you will launch it twice.
// global-setup.ts: runner-agnostic readiness check (Node 18+ has global fetch).
// Export this from whatever global setup hook your test runner provides.
const HEALTH_URL = process.env.HEALTH_URL ?? '';
const INTERVAL_MS = 250; // pause between attempts
const TIMEOUT_MS = 60_000; // hard limit so setup never hangs
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
export default async function waitForServer(): Promise<void> {
const deadline = Date.now() + TIMEOUT_MS;
let lastError = 'no response yet';
while (Date.now() < deadline) {
try {
// Cap each attempt so a stalled connection can't eat the whole budget.
const res = await fetch(HEALTH_URL, { signal: AbortSignal.timeout(2_000) });
if (res.status === 200) return; // app finished initializing
lastError = `status ${res.status}`; // up but not ready (e.g. 503)
} catch (err) {
// ECONNREFUSED etc. means the port isn't bound yet: keep polling.
lastError = err instanceof Error ? err.message : String(err);
}
await sleep(INTERVAL_MS);
}
throw new Error(
`Server not ready at ${HEALTH_URL} after ${TIMEOUT_MS} ms (last: ${lastError}). ` +
'Is the continuous serve task running?'
);
}
A global-setup function polls the health endpoint every 250 ms. It treats connection errors and non-200 responses as "not ready yet" and fails with a clear message after 60 seconds instead of hanging.
Caching, inferred plugin targets and CI with nx affected
Don't cache the server
A continuous task never exits, so it never produces a finished result Nx could replay. Keep serve uncached and leave caching to the e2e target. That creates a correctness risk: the e2e cache key must change whenever the backend changes. If the e2e project only reaches the API over HTTP and never imports it, the project graph has no edge between them, and dependency-based inputs such as ^production won't include backend files. Add the backend to the e2e project's implicitDependencies, or list its source in explicit inputs. Without that, editing a controller can return a green cached result for code that was never tested.
Inspect inferred targets
Plugins can infer serve and e2e targets, and their defaults have changed between Nx releases. Run nx show project api to see the resolved configuration, including whether serve has continuous: true and what dependsOn expands to. If the output doesn't match what you need, set the target explicitly in project.json, which takes precedence over the inferred version. Check the docs for your installed Nx version rather than relying on remembered defaults.
CI and ports
nx affected -t e2e builds a task graph that contains only the affected e2e targets and the continuous tasks they depend on. Untouched backends never start. Nx identifies each task by project, target and configuration, so two e2e projects that depend on the same serve share one instance. Two different backends that both default to port 3000 will collide when their e2e runs execute in parallel. Give each backend its own port, for example through an e2e configuration on serve, and point each test runner's base URL at that port.
{
"name": "api-e2e",
"projectType": "application",
"implicitDependencies": ["api"],
"targets": {
"e2e": {
"executor": "nx:run-commands",
"dependsOn": [
{ "projects": ["api"], "target": "serve" }
],
"cache": true,
"inputs": [
"default",
"^production",
"{workspaceRoot}/apps/api/src/**/*"
],
"options": {
"cwd": "apps/api-e2e",
"command": "BASE_URL= npx playwright test"
}
}
}
}
An e2e project.json that depends on the api project's continuous serve target. It reads its base URL from a port reserved for that backend. implicitDependencies and an explicit inputs entry keep backend edits in the cache key, and named inputs like default must exist in nx.json.
How can continuous tasks save engineering time?
The time savings come from removing manual steps and recurring failure modes, not from making the tests themselves faster.
- One command instead of a checklist. Without continuous tasks, running e2e locally often means opening a second terminal, starting the API with the right env file, waiting, then running the tests. With
dependsOn,nx e2e api-e2edoes all of it. New team members don't need to learn the sequence. - No orphaned-port cleanup. Because Nx signals the servers it started when the e2e task ends, developers spend less time finding and killing stale processes after a failed or interrupted run, provided the server handles SIGTERM correctly.
- Fewer scripts to maintain. Start-poll-kill wrapper scripts tend to drift between local and CI versions. Moving the lifecycle into
project.jsonleaves one definition that both environments use. - Less CI work on unrelated changes. With
nx affected -t e2e, backends start only for affected e2e targets, and a correctly keyed e2e cache can replay results when neither the tests nor the backend changed. - Race conditions fixed once. A readiness check committed to the repository removes a class of intermittent failures for everyone, instead of each developer working around it with a local sleep.
Illustrative estimate. The inputs here are assumed, not measured. Assume a team of 10 engineers who each run e2e locally 5 times a week. Also assume the manual start-and-wait routine costs 2 minutes per run, and that each engineer hits one stale-port or startup-race problem per week that takes 15 minutes to diagnose. Manual setup then costs 10 × 5 × 2 = 100 minutes a week, and debugging costs 10 × 15 = 150 minutes a week, for roughly 4 hours a week in total. If continuous tasks plus a readiness check removed most of that, the team would get back a few engineer-hours each week. Substitute your own run counts and failure rates. The result depends heavily on how often your current setup actually breaks.
When should you avoid Nx continuous tasks, and what are the alternatives?
Continuous tasks have costs that are easy to miss until they cause problems.
Coupling to Nx. Once the server starts through dependsOn, running the test runner directly (for example, invoking Playwright from an IDE) no longer starts a backend. You need a fallback path. Two common options are a webServer block that reuses an already-running server, or a documented manual step for starting the server first.
Signal-dependent teardown. Nx stops continuous tasks by sending signals. A server that ignores SIGTERM, or a wrapper script that spawns a child process without forwarding signals to it, can leave orphaned processes behind. This happens most often after Ctrl+C, and it shows up later as "port already in use" errors.
Heavier runs. Every e2e invocation now builds and boots a server. Declare continuous dependencies only on e2e targets. If you add them to build or test, every unrelated build or unit test run pays that cost too.
Stateful infrastructure. Databases and message brokers are usually better run as containers or CI service definitions. Images already exist for them, health checks are built in, and they don't need to be rebuilt from source.
| Approach | Lifecycle owner | Local/CI parity | Readiness | Teardown reliability | Maintenance cost |
|---|---|---|---|---|---|
| Nx continuous tasks | Nx | High, if CI uses Nx | Your own check | Depends on signal handling | Low |
Test-runner webServer |
Test runner | High | Built-in URL/port polling | Good | Low, per runner |
| Backgrounded shell script | Script | Often drifts | Manual | Poor | High |
| Containers / CI services | Docker or CI platform | Medium, separate configs | Health checks | Good | Medium |
Why are my Nx e2e tests failing with connection refused?
Connection refused means nothing accepted the TCP connection at that host and port. The message is identical whether the server is still booting, has died, or is listening somewhere else, so you have to confirm each cause separately.
| Symptom | Likely cause | How to confirm | Fix |
|---|---|---|---|
| First tests fail, later ones pass | e2e started before the server was listening | Server log shows "listening" after the first test error | Add a readiness check against a real endpoint |
| Fails only on a second local run | Leaked process from an earlier run holds the port | lsof -i :<port> shows a stale PID |
Kill it and make the server exit cleanly on SIGTERM |
| Every request refused | Server crashed on startup | Serve task output shows a stack trace or a non-zero exit | Fix the startup error, such as missing env vars or migrations |
| Refused, or wrong data returned | Wrong configuration started, so the port or env differs | Inspect the resolved target | Pin configuration in the dependsOn entry |
Find the server's own output
The test runner only reports the symptom. The cause is in the serve task's output. In the interactive terminal UI, select the serve task to see its log. In CI or with --outputStyle=stream, each line is prefixed with its project:target, so you can search for the serve prefix and read what it printed before the first test failed.
Confirm what Nx resolved
Run nx show project <app> --json to see the final target after inferred plugin targets and targetDefaults are merged. Check that the serve target is marked continuous, which configuration e2e depends on, and what port that configuration uses.
Why fix it in Nx config
A sleep 10 or a personal kill alias fixes the problem for one developer on one machine. Every other developer then debugs the same race separately. A readiness check and a pinned configuration in project.json apply to every run, locally and in CI. That turns a recurring intermittent failure into a configuration problem you solve once.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to nx continuous tasks, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Changing a shared variable is one edit and one review instead of editing every service's
.envby hand.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.