> 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/frontend-instrumentation-static.md).

# Frontend Instrumentation (static)

Instrument a built web application with slnodejs for browser coverage: commands, output, multiple environments, the agent configuration file, Collector and token options.

> **Applies to:** web applications that run in a browser: React, Angular, Vue, Svelte and other bundled JavaScript.

Front-end code is instrumented **before deployment**. `slnodejs` writes an instrumented copy of your built files. Each instrumented file loads the [SeaLights Browser Agent](https://docs.sealights.io/knowledgebase/setup-and-configuration/sealights-agents-and-plugins/browser-agent.md), which collects coverage in the browser while tests run and sends it for the build's lab ID. You deploy the instrumented copy to the test environment instead of the original build.

This page covers the `slnodejs` side: which command to run and what it writes. Framework-specific setups (Angular, React, Vue, Vite, webpack, esbuild, Rsbuild, Rollup, micro-frontends) are in [Browser Agent → Framework and Bundler Setups](https://docs.sealights.io/knowledgebase/setup-and-configuration/sealights-agents-and-plugins/browser-agent/framework-setups.md), and every flag is explained in the [Flags and Settings Guide](https://docs.sealights.io/knowledgebase/setup-and-configuration/sealights-agents-and-plugins/browser-agent/flags-and-settings-guide.md). How the agent behaves in the browser (lab ID resolution, runtime overrides, context propagation, content security policy, troubleshooting) is in the [Browser Agent](https://docs.sealights.io/knowledgebase/setup-and-configuration/sealights-agents-and-plugins/browser-agent.md) section.

{% hint style="danger" %}
Never deploy instrumented code to production. Deploy it to test environments only.
{% endhint %}

## Choose a command <a href="#choose-a-command" id="choose-a-command"></a>

| Goal                                                                  | Command                                                                                                 |
| --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
| Scan the build and instrument it in one step (**recommended**)        | `slnodejs scan --instrumentForBrowsers --outputPath <dir>`                                              |
| Instrument again without reporting a new build                        | `slnodejs scan --instrumentForBrowsers --instrumentationOnly --outputPath <dir>`                        |
| Instrument separately from the scan, for example once per environment | Scan with `--useRelativeSlMapping`, then `slnodejs instrument --workspacePath <dir> --outputPath <dir>` |

{% stepper %}
{% step %}

### Build with source maps

Your build must produce source maps with column information next to the bundles. See [Scanning → Front-end builds](https://docs.sealights.io/knowledgebase/setup-and-configuration/sealights-agents-and-plugins/node.js-agent/scanning-your-application.md#scanning-a-frontend-build-bundled).
{% endstep %}

{% step %}

### Scan and instrument

```bash
printf '%s' "$SEALIGHTS_AGENT_TOKEN" > sltoken.txt
npx slnodejs config --tokenFile sltoken.txt --appName my-web-app --branchName main --buildName "1.0.$BUILD_NUMBER"
npx slnodejs scan --tokenFile sltoken.txt --buildSessionIdFile buildSessionId \
  --scanDir dist --scmType git --es6Modules \
  --instrumentForBrowsers --outputPath sl_dist \
  --labId qa-env \
  --excludeSourceMapFiles skipCopy
```

| Flag                                           | Why                                                                                                                                    |
| ---------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `--instrumentForBrowsers --outputPath sl_dist` | Writes the instrumented copy to `sl_dist`.                                                                                             |
| `--es6Modules`                                 | Most modern bundles are ES modules.                                                                                                    |
| `--labId qa-env`                               | The lab ID the browser agent reports with. Coverage goes to the test stage open on that lab. Without it, the build session ID is used. |
| `--excludeSourceMapFiles skipCopy`             | Keeps the source maps out of the deployed output.                                                                                      |
| {% endstep %}                                  |                                                                                                                                        |

{% step %}

### Deploy the instrumented output

Deploy the contents of `sl_dist` to the test environment in place of `dist`. For example, swap the folders before your deployment step:

```bash
mv dist dist_original
mv sl_dist dist
# deploy dist/ to the test environment
```

Build production artifacts from a clean build, not from this folder.
{% endstep %}

{% step %}

### Check that it works

Open a page of the test environment, then the browser developer tools console. A working agent logs `Sealights browser version <version> has been loaded`, and `window.$SealightsAgent` is defined. See [Browser Agent → Check that it works](https://docs.sealights.io/knowledgebase/setup-and-configuration/sealights-agents-and-plugins/browser-agent/setting-up-browser-coverage.md#check-that-it-works).
{% endstep %}

{% step %}

### Run your tests

Run the tests with a test stage open on the same lab ID. 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 %}

## What `slnodejs` writes <a href="#output" id="output"></a>

* All files of the scanned directory are copied to `--outputPath`, and the JavaScript files in the copy are instrumented. The scanned directory is not changed, except with `--excludeSourceMapFiles skipAndDelete`.
* `--outputPath` must differ from the input directory (`--scanDir` for `scan`, `--workspacePath` for `instrument`).
* Files matched by `.slignore` are not instrumented. Files matched by `.slignore.instrument` are scanned but not instrumented. By default, common framework packages (Angular, React, Vue, `core-js`, `tslib` and others) inside the bundles are not instrumented. See [Configuration → Ignore files](https://docs.sealights.io/knowledgebase/setup-and-configuration/sealights-agents-and-plugins/node.js-agent/configuration.md#ignore-files).
* Vue single-file components (`.vue`) built with webpack (vue-loader) or Vite are reported on the `.vue` file itself. The `.vue` source files must be present where `slnodejs scan` runs.

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

Each environment needs its own lab ID, so coverage from one environment does not land in another environment's test stage.

**Option A: instrument once per environment.** Scan once with `--useRelativeSlMapping`, then run `instrument` for each environment with its own `--labId` and `--outputPath`:

```bash
npx slnodejs scan --tokenFile sltoken.txt --buildSessionIdFile buildSessionId \
  --scanDir dist --scmType git --es6Modules --useRelativeSlMapping

npx slnodejs instrument --tokenFile sltoken.txt --buildSessionIdFile buildSessionId \
  --workspacePath dist --outputPath sl_dist_qa --labId qa-env
npx slnodejs instrument --tokenFile sltoken.txt --buildSessionIdFile buildSessionId \
  --workspacePath dist --outputPath sl_dist_staging --labId staging-env
```

**Option B: instrument once, set the lab ID at runtime.** Each environment sets `window["__sl.labId__"]` in a script that runs before the instrumented files, for example from the environment's HTML template:

```html
<script>window['__sl.labId__'] = 'staging-env';</script>
```

It takes precedence over the lab ID the build was instrumented with. See [Browser Agent → Lab ID](https://docs.sealights.io/knowledgebase/setup-and-configuration/sealights-agents-and-plugins/browser-agent/configuration.md#lab-id).

## Agent configuration file <a href="#agent-configuration-file" id="agent-configuration-file"></a>

By default, the browser agent configuration is embedded in each instrumented file. With `--splitPreambleIntoFile`, it is written to one separate file in the output directory (`sl-preamble-config.js`, or `--preambleFileName`), which the browser loads from `{preambleFileUrl}/{preambleFileName}`.

```bash
npx slnodejs scan --tokenFile sltoken.txt --buildSessionIdFile buildSessionId \
  --scanDir dist --scmType git --es6Modules --instrumentForBrowsers --outputPath sl_dist \
  --splitPreambleIntoFile --preambleFileUrl https://app.qa.example.com/static
```

* Deploy the configuration file with the instrumented files, and serve it non-cacheable. When the browser cannot load it, the agent does not load.
* Without `--preambleFileUrl`, or with a relative value, the browser resolves the file relative to the page URL (or `<base href>`). On a deep route of a single-page application (for example `/orders/42`) it then requests the file below that route and gets a 404. Pass a full URL, or set `<base href>`.
* `--preambleFileUrl` accepts a full URL, or a relative path without a leading or trailing `/`.

**Toggle-based instrumentation.** With `--toggleBasedBrowserInstrumentation` (which requires `--splitPreambleIntoFile`), `slnodejs` writes `<name>_original.js` and `<name>_instrumented.js` and replaces each file with a loader. The loader checks for `/sl-preamble-config.js` at the web server root (whatever `--preambleFileName` and `--preambleFileUrl` say) and loads the instrumented or the original file as a classic script. This lets one deployment run with or without SeaLights, for classic-script bundles; it does not fit ES module bundles. Without `--splitPreambleIntoFile`, `slnodejs scan` prints `toggleBasedBrowserInstrumentation can only be used when splitPreambleIntoFile is true.` and neither scans nor instruments. See [the limits](https://docs.sealights.io/knowledgebase/setup-and-configuration/sealights-agents-and-plugins/browser-agent/flags-and-settings-guide.md#togglebasedbrowserinstrumentation).

## Collector and token exposure <a href="#collector-and-token" id="collector-and-token"></a>

By default, the agent token is written into the browser configuration of every instrumented build, so anyone who can open the deployed application can read it.

To keep it out, send browser coverage through a SeaLights Collector:

```bash
npx slnodejs scan --tokenFile sltoken.txt --buildSessionIdFile buildSessionId \
  --scanDir dist --scmType git --es6Modules --instrumentForBrowsers --outputPath sl_dist \
  --collectorUrl https://collector.qa.example.com:16500/api \
  --excludeTokenFromBrowserConfig
```

The preamble then loads the agent from the Collector, and the agent sends coverage to the Collector. Without `--collectorUrl` (or `--overrideServer`), `--excludeTokenFromBrowserConfig` only prints a warning, and the browser agent calls SeaLights without a token. See also [Frontend - Prevent Token Exposure in Instrumented Applications](https://docs.sealights.io/knowledgebase/setup-and-configuration/troubleshooting-faq/node-javascript/frontend-prevent-token-exposure-in-instrumented-applications.md).

## Restrict where the agent loads <a href="#restrict-where-the-agent-loads" id="restrict-where-the-agent-loads"></a>

`--allowedDomains app.qa.example.com,app.staging.example.com` loads the browser agent only when the page's host name is in the list. Use it when the same instrumented files can be served on other domains.

## Large applications and page load time <a href="#large-applications" id="large-applications"></a>

| Symptom                                             | Option                                                                                                                                                                            |
| --------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Tests time out on page load after instrumentation   | `SL_reduceInstrumentedFileSize=true` on the `scan --instrumentForBrowsers` step (instruments without line-level counters; much smaller files). `instrument` does this by default. |
| The sl-mapping download is large                    | `--footprintsMapping server` (SeaLights resolves the coverage; the browser does not download the sl-mapping).                                                                     |
| Code-split or lazy-loaded chunks                    | No extra setup: every chunk of an instrumented build reports to the same build session.                                                                                           |
| Vendor bundles without source maps are instrumented | `--skipInstrumentingFilesWithoutSourceMap`, or list them in `.slignore.instrument`.                                                                                               |

## Context propagation to back-end services <a href="#context-propagation" id="context-propagation"></a>

To attribute back-end coverage to the same browser test, instrument with `--enableOpenTelemetry` and `--allowCORS`. See [Browser Agent → Context Propagation](https://docs.sealights.io/knowledgebase/setup-and-configuration/sealights-agents-and-plugins/browser-agent/context-propagation.md).

## Settings without a flag <a href="#settings-without-a-flag" id="settings-without-a-flag"></a>

`scan --instrumentForBrowsers` and `instrument` also read these environment variables:

| Variable                        | Effect                                                                             |
| ------------------------------- | ---------------------------------------------------------------------------------- |
| `SL_reduceInstrumentedFileSize` | `true` instruments without line-level counters.                                    |
| `SL_minifyInstrumentedOutput`   | `true` minifies the instrumented output.                                           |
| `SL_inProcessInstrumentation`   | `true` instruments in the `slnodejs` process instead of a pool of child processes. |
| `SL_fileExtensions`             | Replaces the list of scanned and instrumented extensions, for example `.js,.mjs`.  |

Settings that are written into the build for the browser agent (for example `SL_blockBrowserHttpTraffic`) are in [Browser Agent → Configuration](https://docs.sealights.io/knowledgebase/setup-and-configuration/sealights-agents-and-plugins/browser-agent/configuration.md#settings-read-from-the-instrumentation-environment).

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

* Agent not loading, no footprints, sl-mapping not found, missing context headers: [Browser Agent → Troubleshooting](https://docs.sealights.io/knowledgebase/setup-and-configuration/sealights-agents-and-plugins/browser-agent/troubleshooting.md).
* `instrument` fails with `Build was performed without 'useRelativeSlMapping' flag`: scan the build with `--useRelativeSlMapping`.
* `instrument` rejects `--scanDir`: use `--workspacePath`.
* [JS: No Front-End Coverage](https://docs.sealights.io/knowledgebase/setup-and-configuration/troubleshooting-faq/node-javascript/js-no-front-end-coverage.md), [CSP Errors in Instrumented JS Frontend Apps](https://docs.sealights.io/knowledgebase/setup-and-configuration/troubleshooting-faq/node-javascript/csp-errors-in-instrumented-js-frontend-apps.md).


---

# 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/frontend-instrumentation-static.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.
