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

# Using the Node module

> Run Lighthouse programmatically from Node.js to integrate audits into custom scripts, CI pipelines, and tooling.

The Lighthouse Node module lets you run audits from JavaScript code and consume results as structured data. This is useful when you need to integrate Lighthouse into a custom script, build tool, or CI system.

## Basic usage

Install Lighthouse as a project dependency:

```bash theme={null}
npm install --save-dev lighthouse chrome-launcher
```

Then run it programmatically:

```js theme={null}
import fs from 'fs';
import lighthouse from 'lighthouse';
import * as chromeLauncher from 'chrome-launcher';

const chrome = await chromeLauncher.launch({chromeFlags: ['--headless']});
const options = {
  logLevel: 'info',
  output: 'html',
  onlyCategories: ['performance'],
  port: chrome.port,
};
const runnerResult = await lighthouse('https://example.com', options);

// `.report` is the HTML report as a string
const reportHtml = runnerResult.report;
fs.writeFileSync('lhreport.html', reportHtml);

// `.lhr` is the Lighthouse Result as a JS object
console.log('Report is done for', runnerResult.lhr.finalDisplayedUrl);
console.log('Performance score was', runnerResult.lhr.categories.performance.score * 100);

await chrome.kill();
```

## Function signature

```js theme={null}
lighthouse(url, flags, config, page)
```

| Parameter | Type             | Required                  | Description                                                                    |
| --------- | ---------------- | ------------------------- | ------------------------------------------------------------------------------ |
| `url`     | `string`         | No (if using `auditMode`) | The URL to audit.                                                              |
| `flags`   | `object`         | No                        | Run options that override config settings.                                     |
| `config`  | `object`         | No                        | Full Lighthouse configuration object. Defaults to the built-in default config. |
| `page`    | `Puppeteer.Page` | No                        | An existing Puppeteer page to use instead of launching a new browser.          |

Returns `Promise<RunnerResult | undefined>`.

## Key flags

| Flag             | Type                                                   | Description                                                                                                |
| ---------------- | ------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------- |
| `logLevel`       | `'silent' \| 'error' \| 'warn' \| 'info' \| 'verbose'` | Controls log output. Use `'info'` to see progress.                                                         |
| `output`         | `'html' \| 'json' \| 'csv'`                            | Report format. The result is returned as a string in `.report`.                                            |
| `onlyCategories` | `string[]`                                             | Limit audits to the specified categories: `'performance'`, `'accessibility'`, `'best-practices'`, `'seo'`. |
| `port`           | `number`                                               | DevTools Protocol port of the Chrome instance to connect to. You must launch Chrome separately.            |

```js theme={null}
// Performance-only run
const flags = {onlyCategories: ['performance']};
await lighthouse(url, flags);

// Enable logging
const flags = {logLevel: 'info'};
await lighthouse('https://example.com', flags);
```

## Differences from CLI flags

Some CLI flags behave differently or are ignored when using the Node module.

| CLI flag               | Behavior in Node module                                                        |
| ---------------------- | ------------------------------------------------------------------------------ |
| `port`                 | Only specifies which port to connect to. Chrome is not launched automatically. |
| `chromeFlags`          | Ignored. Chrome is not launched for you.                                       |
| `outputPath`           | Ignored. Output is returned as a string in `.report`.                          |
| `saveAssets`           | Ignored. Artifacts are returned in `.artifacts`.                               |
| `view`                 | Ignored. Use the `open` npm package if you want this behavior.                 |
| `enableErrorReporting` | Ignored. Error reporting is always disabled in the Node module.                |
| `listAllAudits`        | Ignored. Not relevant in programmatic use.                                     |
| `listTraceCategories`  | Ignored. Not relevant in programmatic use.                                     |
| `configPath`           | Ignored. Pass the config object as the third argument to `lighthouse()`.       |
| `preset`               | Ignored. Pass the config object as the third argument to `lighthouse()`.       |
| `verbose`              | Ignored. Use `logLevel: 'verbose'` instead.                                    |
| `quiet`                | Ignored. Use `logLevel: 'silent'` instead.                                     |

## The RunnerResult object

`lighthouse()` resolves to a `RunnerResult` with three properties:

| Property     | Type                 | Description                                                                                                     |
| ------------ | -------------------- | --------------------------------------------------------------------------------------------------------------- |
| `.report`    | `string \| string[]` | The formatted report. A `string` for a single output format, or `string[]` when multiple formats are requested. |
| `.lhr`       | `LH.Result`          | The full Lighthouse Result object as a plain JS object. Contains all scores, audit results, and metadata.       |
| `.artifacts` | `LH.Artifacts`       | Raw gathered artifacts from the page (traces, network logs, DOM snapshots, etc.).                               |

```js theme={null}
const runnerResult = await lighthouse('https://example.com', {output: ['html', 'json']});

// HTML report
fs.writeFileSync('report.html', runnerResult.report[0]);

// JSON report
fs.writeFileSync('report.json', runnerResult.report[1]);

// Performance score
const score = runnerResult.lhr.categories.performance.score * 100;
console.log(`Performance: ${score}`);

// Check a specific audit
const fcp = runnerResult.lhr.audits['first-contentful-paint'];
console.log(`FCP: ${fcp.displayValue}`);
```

## Custom configuration

Pass a config object as the third argument to extend or replace the default configuration:

```js theme={null}
const config = {
  extends: 'lighthouse:default',
  settings: {
    onlyAudits: [
      'speed-index',
      'interactive',
    ],
  },
};

const result = await lighthouse('https://example.com', {}, config);
```

## Testing on a mobile device

To run Lighthouse against a real Android device connected via USB:

<Steps>
  <Step title="Install and start adb">
    ```bash theme={null}
    adb kill-server
    adb devices -l
    ```
  </Step>

  <Step title="Enable USB debugging on the device">
    On the Android device, go to **Settings** > **Developer options** and enable **USB debugging**.
  </Step>

  <Step title="Forward the DevTools port">
    ```bash theme={null}
    adb forward tcp:9222 localabstract:chrome_devtools_remote
    ```
  </Step>

  <Step title="Run Lighthouse against the forwarded port">
    ```bash theme={null}
    lighthouse --port=9222 \
      --screenEmulation.disabled \
      --throttling.cpuSlowdownMultiplier=1 \
      --throttling-method=provided \
      https://example.com
    ```

    Or from Node:

    ```js theme={null}
    const result = await lighthouse('https://example.com', {
      port: 9222,
      screenEmulation: {disabled: true},
      throttling: {cpuSlowdownMultiplier: 1},
      throttlingMethod: 'provided',
    });
    ```
  </Step>
</Steps>

## Testing a site with an untrusted certificate

When Chrome encounters an untrusted TLS certificate, it cannot load the page and most audit results will be errors.

If you control the certificate (for example, a self-signed cert for local development), the recommended solution is to add it to your system's trusted certificate store.

Alternatively, you can instruct Chrome to ignore certificate errors:

```bash theme={null}
lighthouse https://localhost:8443 --chrome-flags="--ignore-certificate-errors"
```

<Warning>
  The `--ignore-certificate-errors` flag disables TLS validation for all content loaded by the page, including third-party scripts and iframes. This opens the page to man-in-the-middle attacks. Only use this flag in controlled development environments.
</Warning>

## Using Lighthouse as a trace processor

Lighthouse can analyze pre-collected trace and DevTools log files without launching a browser. This is useful for reprocessing data collected by other tools such as WebPageTest or ChromeDriver.

Provide a config that sets `auditMode` to the directory containing the artifacts:

```json theme={null}
{
  "settings": {
    "auditMode": "/path/to/artifacts/"
  },
  "audits": [
    "user-timings",
    "critical-request-chains"
  ],
  "categories": {
    "performance": {
      "name": "Performance Metrics",
      "description": "These encapsulate your web app's performance.",
      "audits": [
        {"id": "user-timings", "weight": 1},
        {"id": "critical-request-chains", "weight": 1}
      ]
    }
  }
}
```

Then run with the config path:

```bash theme={null}
lighthouse --config-path=config.json http://www.random.url
```

Artifact files must use `.trace.json` and `.devtoolslog.json` extensions. The `DevtoolsLog` is captured from the Chrome `Network` and `Page` domains.
