Skip to main content
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:
npm install --save-dev lighthouse chrome-launcher
Then run it programmatically:
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

lighthouse(url, flags, config, page)
ParameterTypeRequiredDescription
urlstringNo (if using auditMode)The URL to audit.
flagsobjectNoRun options that override config settings.
configobjectNoFull Lighthouse configuration object. Defaults to the built-in default config.
pagePuppeteer.PageNoAn existing Puppeteer page to use instead of launching a new browser.
Returns Promise<RunnerResult | undefined>.

Key flags

FlagTypeDescription
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.
onlyCategoriesstring[]Limit audits to the specified categories: 'performance', 'accessibility', 'best-practices', 'seo'.
portnumberDevTools Protocol port of the Chrome instance to connect to. You must launch Chrome separately.
// 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 flagBehavior in Node module
portOnly specifies which port to connect to. Chrome is not launched automatically.
chromeFlagsIgnored. Chrome is not launched for you.
outputPathIgnored. Output is returned as a string in .report.
saveAssetsIgnored. Artifacts are returned in .artifacts.
viewIgnored. Use the open npm package if you want this behavior.
enableErrorReportingIgnored. Error reporting is always disabled in the Node module.
listAllAuditsIgnored. Not relevant in programmatic use.
listTraceCategoriesIgnored. Not relevant in programmatic use.
configPathIgnored. Pass the config object as the third argument to lighthouse().
presetIgnored. Pass the config object as the third argument to lighthouse().
verboseIgnored. Use logLevel: 'verbose' instead.
quietIgnored. Use logLevel: 'silent' instead.

The RunnerResult object

lighthouse() resolves to a RunnerResult with three properties:
PropertyTypeDescription
.reportstring | string[]The formatted report. A string for a single output format, or string[] when multiple formats are requested.
.lhrLH.ResultThe full Lighthouse Result object as a plain JS object. Contains all scores, audit results, and metadata.
.artifactsLH.ArtifactsRaw gathered artifacts from the page (traces, network logs, DOM snapshots, etc.).
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:
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:
1

Install and start adb

adb kill-server
adb devices -l
2

Enable USB debugging on the device

On the Android device, go to Settings > Developer options and enable USB debugging.
3

Forward the DevTools port

adb forward tcp:9222 localabstract:chrome_devtools_remote
4

Run Lighthouse against the forwarded port

lighthouse --port=9222 \
  --screenEmulation.disabled \
  --throttling.cpuSlowdownMultiplier=1 \
  --throttling-method=provided \
  https://example.com
Or from Node:
const result = await lighthouse('https://example.com', {
  port: 9222,
  screenEmulation: {disabled: true},
  throttling: {cpuSlowdownMultiplier: 1},
  throttlingMethod: 'provided',
});

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:
lighthouse https://localhost:8443 --chrome-flags="--ignore-certificate-errors"
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.

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:
{
  "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:
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.

Build docs developers (and LLMs) love