> ## 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.

# Node API reference

> Complete reference for using Lighthouse programmatically as a Node module.

The Lighthouse Node API gives you full programmatic control over audits, user flows, and report generation. Install the package first:

```bash theme={null}
npm install lighthouse
# or
yarn add lighthouse
```

<Note>
  Node 22 (LTS) or later is required. Some CLI flags are not available in the Node API — pass configuration directly as the third argument instead.
</Note>

***

## `lighthouse(url, flags, config, page)`

The default export. Runs a full navigation audit against a URL and returns a `RunnerResult`.

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

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

console.log('Performance score:', result.lhr.categories.performance.score * 100);
await chrome.kill();
```

### Parameters

<ParamField path="url" type="string">
  The URL to audit. Optional when running in `auditMode`.
</ParamField>

<ParamField path="flags" type="object" default="{}">
  Runtime flags that override config settings. Common flags include `port`, `output`, `onlyCategories`, and `logLevel`. See [Configuration reference](/api/configuration-reference) for the full list.
</ParamField>

<ParamField path="config" type="object">
  A Lighthouse config object. If omitted, the default config (`lighthouse:default`) is used. See [Configuration reference](/api/configuration-reference).
</ParamField>

<ParamField path="page" type="Puppeteer.Page">
  An existing Puppeteer `Page` instance. If provided, Lighthouse uses it directly instead of connecting via the `port` flag.
</ParamField>

### Return value

Returns `Promise<LH.RunnerResult | undefined>`.

<ResponseField name="lhr" type="object" required>
  The Lighthouse Result object. See [Understanding results](/api/understanding-results).
</ResponseField>

<ResponseField name="report" type="string | string[]" required>
  The formatted report string (HTML, JSON, or CSV). When multiple output formats are requested this is an array.
</ResponseField>

<ResponseField name="artifacts" type="object" required>
  Raw artifacts collected during the run.
</ResponseField>

***

## `startFlow(page, options)`

Creates a `UserFlow` instance to record multiple steps (navigations, timespans, snapshots) in sequence, then generate a single combined flow report.

```js theme={null}
import {startFlow} from 'lighthouse';
import puppeteer from 'puppeteer';

const browser = await puppeteer.launch();
const page = await browser.newPage();

const flow = await startFlow(page, {name: 'Checkout flow'});

await flow.navigate('https://example.com');
await flow.startTimespan({stepName: 'Add to cart'});
await page.click('#add-to-cart');
await flow.endTimespan();
await flow.snapshot({stepName: 'Cart state'});

const report = flow.generateReport();
await browser.close();
```

### Parameters

| Parameter | Type                  | Description                                                                          |
| --------- | --------------------- | ------------------------------------------------------------------------------------ |
| `page`    | `Puppeteer.Page`      | Required. A Puppeteer page instance.                                                 |
| `options` | `LH.UserFlow.Options` | Optional. May include `name` (string) for the flow report title and a base `config`. |

### Return value

Returns `Promise<UserFlow>`. The `UserFlow` instance exposes `.navigate()`, `.startTimespan()`, `.endTimespan()`, `.snapshot()`, and `.generateReport()`.

***

## `navigation(page, requestor, options)`

Performs a single navigation-based audit. This is the function `lighthouse()` calls internally.

```js theme={null}
import {navigation} from 'lighthouse';

const result = await navigation(page, 'https://example.com', {
  config: {extends: 'lighthouse:default'},
  flags: {onlyCategories: ['performance']},
});
```

### Parameters

| Parameter   | Type                                  | Description                                        |
| ----------- | ------------------------------------- | -------------------------------------------------- |
| `page`      | `Puppeteer.Page \| undefined`         | Puppeteer page to use.                             |
| `requestor` | `LH.NavigationRequestor \| undefined` | URL string or a function that triggers navigation. |
| `options`   | `{config?, flags?}`                   | Optional config and flags.                         |

### Return value

Returns `Promise<LH.RunnerResult | undefined>`.

***

## `startTimespan(page, options)`

Begins a timespan audit that records user interactions between `startTimespan` and `endTimespan`. Use this to measure the performance impact of a specific interaction.

```js theme={null}
import {startTimespan} from 'lighthouse';

const {endTimespan} = await startTimespan(page, {flags: {onlyCategories: ['performance']}});

await page.click('#load-more');
await page.waitForSelector('.new-items');

const result = await endTimespan();
```

### Parameters

| Parameter | Type                | Description                |
| --------- | ------------------- | -------------------------- |
| `page`    | `Puppeteer.Page`    | The page to instrument.    |
| `options` | `{config?, flags?}` | Optional config and flags. |

### Return value

Returns `Promise<{endTimespan: () => Promise<LH.RunnerResult | undefined>}>`.

***

## `snapshot(page, options)`

Audits the current state of the page without navigating. Useful for auditing the state of a single-page application after user interaction.

```js theme={null}
import {snapshot} from 'lighthouse';

await page.goto('https://example.com/app');
await page.click('#open-modal');

const result = await snapshot(page, {flags: {onlyCategories: ['accessibility']}});
```

### Parameters

| Parameter | Type                | Description                |
| --------- | ------------------- | -------------------------- |
| `page`    | `Puppeteer.Page`    | The page to snapshot.      |
| `options` | `{config?, flags?}` | Optional config and flags. |

### Return value

Returns `Promise<LH.RunnerResult | undefined>`.

***

## `generateReport(result, format)`

Converts a Lighthouse result or flow result object to a formatted report string.

<CodeGroup>
  ```js HTML report theme={null}
  import {generateReport} from 'lighthouse';

  const html = generateReport(runnerResult.lhr, 'html');
  fs.writeFileSync('report.html', html);
  ```

  ```js JSON report theme={null}
  import {generateReport} from 'lighthouse';

  const json = generateReport(runnerResult.lhr, 'json');
  const data = JSON.parse(json);
  ```

  ```js CSV report theme={null}
  import {generateReport} from 'lighthouse';

  const csv = generateReport(runnerResult.lhr, 'csv');
  fs.writeFileSync('report.csv', csv);
  ```
</CodeGroup>

### Parameters

| Parameter | Type                         | Default  | Description                                                  |
| --------- | ---------------------------- | -------- | ------------------------------------------------------------ |
| `result`  | `LH.Result \| LH.FlowResult` | —        | The result object to format.                                 |
| `format`  | `'html' \| 'json' \| 'csv'`  | `'html'` | Output format. `'csv'` is not supported for `LH.FlowResult`. |

### Return value

Returns `string`.

***

## `auditFlowArtifacts(flowArtifacts, config)`

Re-audits previously collected flow artifacts against an optional config. Useful when you want to change scoring or audits without re-running the browser.

```js theme={null}
import {auditFlowArtifacts} from 'lighthouse';

const flowResult = await auditFlowArtifacts(savedFlowArtifacts, {
  extends: 'lighthouse:default',
  settings: {onlyCategories: ['performance']},
});
```

### Parameters

| Parameter       | Type                        | Description                                                            |
| --------------- | --------------------------- | ---------------------------------------------------------------------- |
| `flowArtifacts` | `LH.UserFlow.FlowArtifacts` | Artifacts from a previous flow run. Includes `gatherSteps` and `name`. |
| `config`        | `LH.Config`                 | Optional config to apply during the audit phase.                       |

### Return value

Returns `Promise<LH.FlowResult>`.

***

## `getAuditList()`

Returns an array of all available built-in audit IDs.

```js theme={null}
import {getAuditList} from 'lighthouse';

const audits = getAuditList();
console.log(audits);
// ['is-on-https', 'redirects-http', 'service-worker', ...]
```

### Return value

Returns `string[]`.

***

## Base classes

### `Audit`

The base class for all Lighthouse audits. Extend this to create custom audits.

```js theme={null}
import {Audit} from 'lighthouse';

class MyAudit extends Audit {
  static get meta() {
    return {
      id: 'my-audit',
      title: 'My custom audit',
      failureTitle: 'My custom audit failed',
      description: 'Checks for a custom condition.',
      requiredArtifacts: ['URL'],
    };
  }

  static audit(artifacts) {
    const passed = artifacts.URL.finalDisplayedUrl.startsWith('https');
    return {score: passed ? 1 : 0};
  }
}

export default MyAudit;
```

### `Gatherer`

The base class for all Lighthouse gatherers. Extend this to collect custom artifacts.

```js theme={null}
import {Gatherer} from 'lighthouse';

class MyGatherer extends Gatherer {
  meta = {
    supportedModes: ['navigation', 'snapshot', 'timespan'],
  };

  async getArtifact(context) {
    const value = await context.driver.executionContext.evaluate(() => {
      return document.title;
    }, {args: []});
    return value;
  }
}

export default MyGatherer;
```

***

## Computed artifact

### `NetworkRecords`

A computed artifact that parses devtools log entries into structured network request objects. Useful when writing custom audits that need network data.

```js theme={null}
import {NetworkRecords} from 'lighthouse';

// Inside an audit's audit() method:
const networkRecords = await NetworkRecords.request(artifacts.DevtoolsLog, context);
const slowRequests = networkRecords.filter(r => r.transferSize > 100_000);
```

***

## Built-in configs

| Export          | Description                                                                   |
| --------------- | ----------------------------------------------------------------------------- |
| `defaultConfig` | The standard Lighthouse config. Equivalent to `lighthouse:default`.           |
| `desktopConfig` | Desktop preset config. Disables mobile emulation and uses desktop throttling. |

```js theme={null}
import lighthouse, {defaultConfig, desktopConfig} from 'lighthouse';

// Run with desktop config
const result = await lighthouse('https://example.com', {port: chrome.port}, desktopConfig);
```

***

## `traceCategories`

An array of Chrome trace category strings that Lighthouse requires for its audits. Pass these to your own tracing setup if you collect traces externally.

```js theme={null}
import {traceCategories} from 'lighthouse';

console.log(traceCategories);
// ['toplevel', 'v8.execute', 'blink.user_timing', ...]
```
