> For the complete documentation index, see [llms.txt](https://docs.sealights.io/knowledgebase/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.sealights.io/knowledgebase/setup-and-configuration/sealights-agents-and-plugins/node.js-agent/capturing-runtime-coverage/backend-instrumentation-dynamic.md).

# Backend Instrumentation (dynamic)

Collect coverage from a running Node.js service with slnodejs run or the preload script: lab IDs, per-test coverage, ES modules, containers.

> **Applies to:** Node.js services, APIs, workers and CLIs (Express, NestJS, Fastify, Koa and others) that run while tests exercise them.

Back-end code is instrumented **at runtime**. You deploy the original code and start the process with the SeaLights test listener, which collects coverage while the process runs and sends it for the process's lab ID. By default the test listener uses NYC; for lower overhead, see [Lightweight V8 Coverage Mode](https://docs.sealights.io/knowledgebase/setup-and-configuration/sealights-agents-and-plugins/node.js-agent/advanced-features/lightweight-v8-coverage-mode.md).

{% stepper %}
{% step %}

### Scan the service

Scan the build first. See [Scanning Your Application](https://docs.sealights.io/knowledgebase/setup-and-configuration/sealights-agents-and-plugins/node.js-agent/scanning-your-application.md). Use the same project root for the scan and for the running process (both default to the working directory).
{% endstep %}

{% step %}

### Start the service with the test listener

Choose how to start it:

| Method                                           | Use when                                                                                                                                   | Limits                                                                                                                     |
| ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------- |
| **`slnodejs run`**                               | You control the start command (script, Dockerfile `CMD`).                                                                                  | None.                                                                                                                      |
| **Preload script** (`node -r` or `NODE_OPTIONS`) | A wrapper starts the process (`npm start`, `pm2`, a platform entry point), or every Node.js process in a test container should be covered. | Settings from environment variables only; no signal forwarding; no HTTP coloring; no NYC coverage for ES modules programs. |

#### Option A: `slnodejs run`

Everything after `--` is the program and its arguments.

{% tabs %}
{% tab title="Bash" %}

```bash
npx slnodejs run \
  --tokenFile sltoken.txt \
  --buildSessionIdFile buildSessionId \
  --labId qa-env \
  -- dist/server.js
```

{% endtab %}

{% tab title="PowerShell" %}

```powershell
npx slnodejs run `
  --tokenFile sltoken.txt `
  --buildSessionIdFile buildSessionId `
  --labId qa-env `
  -- dist/server.js
```

{% endtab %}

{% tab title="Dockerfile" %}

```dockerfile
CMD ["npx", "slnodejs", "run", "--tokenFile", "/run/secrets/sltoken/sltoken.txt", "--buildSessionIdFile", "/app/buildSessionId", "--labId", "qa-env", "--forwardSignals", "--", "dist/server.js"]
```

{% endtab %}
{% endtabs %}

Useful flags:

| Flag                   | When to use                                                                                                                                                                    |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `--labId <id>`         | Always in a shared test environment. One lab ID per environment, the same for all replicas. Without it, the build session ID is the lab ID.                                    |
| `--forwardSignals`     | In containers and process managers, so that `SIGTERM` and `SIGINT` reach the service. `--signalForwardingTimeout` sets how long to wait before `SIGKILL` (default 10 seconds). |
| `--httpServerColoring` | Per-test coverage: attributes coverage of each incoming request to the test named in its headers.                                                                              |
| `--httpClientColoring` | The service calls other instrumented services: passes the current test on outgoing requests.                                                                                   |
| `--es6Modules`         | The program is ES modules (`"type": "module"`).                                                                                                                                |
| `--projectRoot <path>` | The process starts in another directory than the scan ran in.                                                                                                                  |
| `--collectorUrl <url>` | Send coverage through a SeaLights Collector.                                                                                                                                   |
| `--libraries <list>`   | Your own code ships as packages in `node_modules` that must be covered.                                                                                                        |

Every flag: [Command Reference → run](https://docs.sealights.io/knowledgebase/setup-and-configuration/sealights-agents-and-plugins/node.js-agent/command-reference.md#run).

#### Option B: preload script

The preload script starts the test listener inside the normal start command. It reads its settings from environment variables, with these exact names (case-sensitive; each also has an upper-case spelling, for example `SL_LAB_ID`):

{% tabs %}
{% tab title="Bash" %}

```bash
export SL_tokenFile="$PWD/sltoken.txt"
export SL_buildSessionIdFile="$PWD/buildSessionId"
export SL_labId=qa-env
export NODE_OPTIONS="--require $PWD/node_modules/slnodejs/lib/preload.js"
npm start
```

{% endtab %}

{% tab title="PowerShell" %}

```powershell
$env:SL_tokenFile = "$PWD\sltoken.txt"
$env:SL_buildSessionIdFile = "$PWD\buildSessionId"
$env:SL_labId = "qa-env"
$env:NODE_OPTIONS = "--require $PWD\node_modules\slnodejs\lib\preload.js"
npm start
```

{% endtab %}

{% tab title="Dockerfile" %}

```dockerfile
ENV SL_tokenFile=/run/secrets/sltoken/sltoken.txt \
    SL_buildSessionIdFile=/app/buildSessionId \
    SL_labId=qa-env \
    NODE_OPTIONS="--require /app/node_modules/slnodejs/lib/preload.js"
CMD ["node", "dist/server.js"]
```

{% endtab %}

{% tab title="Single process (-r)" %}

```bash
SL_labId=qa-env node -r ./node_modules/slnodejs/lib/preload.js dist/server.js
```

Without `SL_tokenFile` and `SL_buildSessionIdFile`, the preload script uses `./sltoken.txt` and `./buildSessionId`.
{% endtab %}
{% endtabs %}

{% hint style="warning" %}
Only `SL_token`, `SL_tokenFile`, `SL_buildSessionId`, `SL_buildSessionIdFile`, `SL_labId`, `SL_projectRoot`, `SL_collectorUrl` and `SL_proxy` (or their upper-case spellings such as `SL_LAB_ID`) are read. Other spellings, for example `SL_labid` or `SL_tokenfile`, are ignored without a warning.
{% endhint %}

`NODE_OPTIONS` applies to every Node.js process started in that shell or container, including build tools. Set it only in the environment that runs the service, or use `node -r` for a single process.

If the test listener cannot start, the preload script runs the original command without SeaLights.
{% endstep %}

{% step %}

### Check that it works

1. Start the service. The console shows the build session and lab ID, and the log shows `Running agent using NYC` (or `Running agent using lean V8 coverage listener`).
2. If the console shows `Sealights is disabled, running command without sealights`, the agent could not start; see [Troubleshooting](https://docs.sealights.io/knowledgebase/setup-and-configuration/sealights-agents-and-plugins/node.js-agent/troubleshooting.md#tests-or-the-application-run-but-sealights-reports-nothing).
3. Open the [Agent Monitor](https://docs.sealights.io/knowledgebase/setup-and-configuration/monitoring/sealights-cockpit/agent-monitor.md) and check that the agent appears with the expected lab ID.
4. Open a test stage on the same lab, send at least one request, close the test stage, and check the coverage on the dashboard.
   {% endstep %}

{% step %}

### Run your tests

Open a test stage on the service's lab while the tests run. See [Capturing Tests → Functional tests](https://docs.sealights.io/knowledgebase/setup-and-configuration/sealights-agents-and-plugins/node.js-agent/capturing-tests.md#functional-tests).
{% endstep %}
{% endstepper %}

## Multiple environments and replicas <a href="#multiple-environments-and-replicas" id="multiple-environments-and-replicas"></a>

* Use the **same lab ID** for every replica of the service in one environment.
* Use a **different lab ID** for each environment, for example `qa-env` and `staging-env`.
* Use the **same lab ID** for all services (and the front end) that are tested together in one environment.

## Child processes and cluster workers <a href="#child-processes" id="child-processes"></a>

If the service forks workers (`child_process.fork`, `cluster`, process pools) that run your code, set `SL_enableChildProcessPatcher=true` so the agent also starts in those processes.

## Troubleshooting <a href="#troubleshooting" id="troubleshooting"></a>

| Symptom                                                                                             | Cause and fix                                                                                                                                                                                                                                                                                                                                                                    |
| --------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `error: option '--useinitialcolor <useinitialcolor>' argument missing`                              | `--useinitialcolor` takes a value: `--useinitialcolor true`. It is meant for test runners started with `run`, not for services.                                                                                                                                                                                                                                                  |
| `Sealights is disabled, running command without sealights`                                          | The token or build session ID is missing or invalid. Check the file paths and that the build session comes from the same SeaLights account.                                                                                                                                                                                                                                      |
| The agent appears, but coverage is 0%                                                               | No test stage was open on the service's lab ID, or the project root differs from the scan. See [Troubleshooting → Coverage is missing or low](https://docs.sealights.io/knowledgebase/setup-and-configuration/sealights-agents-and-plugins/node.js-agent/troubleshooting.md#coverage-is-missing-or-low).                                                                         |
| The agent does not appear with the preload script                                                   | `NODE_OPTIONS` was replaced by a later layer (for example the base image or `npm` scripts), or the variable names are misspelled. Print `NODE_OPTIONS` in the running process.                                                                                                                                                                                                   |
| `slnodejs` rejects a program argument as an unknown option, or the program receives SeaLights flags | Put `--` between the SeaLights flags and the program. See [Understanding the `--` separator](https://docs.sealights.io/knowledgebase/setup-and-configuration/troubleshooting-faq/node-javascript/understanding-the-double-dash-separator-in-slnodejs-run-commands.md).                                                                                                           |
| The service runs out of memory or starts slowly with the agent                                      | See [NodeJS: Memory Usage Explained](https://docs.sealights.io/knowledgebase/setup-and-configuration/troubleshooting-faq/node-javascript/nodejs-memory-usage-explained.md), or use [Lightweight V8 Coverage Mode](https://docs.sealights.io/knowledgebase/setup-and-configuration/sealights-agents-and-plugins/node.js-agent/advanced-features/lightweight-v8-coverage-mode.md). |

See also [dryRun](https://docs.sealights.io/knowledgebase/setup-and-configuration/sealights-agents-and-plugins/node.js-agent/advanced-features/dryrun-command-troubleshooting-and-validation.md) to check the scan locally.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.sealights.io/knowledgebase/setup-and-configuration/sealights-agents-and-plugins/node.js-agent/capturing-runtime-coverage/backend-instrumentation-dynamic.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
