Research
Security News
Quasar RAT Disguised as an npm Package for Detecting Vulnerabilities in Ethereum Smart Contracts
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
lighthouse
Advanced tools
Lighthouse is an open-source, automated tool for improving the quality of web pages. It can be run against any web page, public or requiring authentication. It has audits for performance, accessibility, progressive web apps, SEO, and more.
Performance Audits
This feature allows you to run performance audits on a web page. The code sample demonstrates how to launch a headless Chrome instance, run Lighthouse against a URL, and log the performance score.
const lighthouse = require('lighthouse');
const chromeLauncher = require('chrome-launcher');
(async () => {
const chrome = await chromeLauncher.launch({chromeFlags: ['--headless']});
const options = {logLevel: 'info', output: 'json', onlyCategories: ['performance'], port: chrome.port};
const runnerResult = await lighthouse('https://example.com', options);
console.log('Report is done for', runnerResult.lhr.finalUrl);
console.log('Performance score was', runnerResult.lhr.categories.performance.score * 100);
await chrome.kill();
})();
Accessibility Audits
This feature allows you to run accessibility audits on a web page. The code sample demonstrates how to launch a headless Chrome instance, run Lighthouse against a URL, and log the accessibility score.
const lighthouse = require('lighthouse');
const chromeLauncher = require('chrome-launcher');
(async () => {
const chrome = await chromeLauncher.launch({chromeFlags: ['--headless']});
const options = {logLevel: 'info', output: 'json', onlyCategories: ['accessibility'], port: chrome.port};
const runnerResult = await lighthouse('https://example.com', options);
console.log('Report is done for', runnerResult.lhr.finalUrl);
console.log('Accessibility score was', runnerResult.lhr.categories.accessibility.score * 100);
await chrome.kill();
})();
SEO Audits
This feature allows you to run SEO audits on a web page. The code sample demonstrates how to launch a headless Chrome instance, run Lighthouse against a URL, and log the SEO score.
const lighthouse = require('lighthouse');
const chromeLauncher = require('chrome-launcher');
(async () => {
const chrome = await chromeLauncher.launch({chromeFlags: ['--headless']});
const options = {logLevel: 'info', output: 'json', onlyCategories: ['seo'], port: chrome.port};
const runnerResult = await lighthouse('https://example.com', options);
console.log('Report is done for', runnerResult.lhr.finalUrl);
console.log('SEO score was', runnerResult.lhr.categories.seo.score * 100);
await chrome.kill();
})();
Progressive Web App (PWA) Audits
This feature allows you to run Progressive Web App (PWA) audits on a web page. The code sample demonstrates how to launch a headless Chrome instance, run Lighthouse against a URL, and log the PWA score.
const lighthouse = require('lighthouse');
const chromeLauncher = require('chrome-launcher');
(async () => {
const chrome = await chromeLauncher.launch({chromeFlags: ['--headless']});
const options = {logLevel: 'info', output: 'json', onlyCategories: ['pwa'], port: chrome.port};
const runnerResult = await lighthouse('https://example.com', options);
console.log('Report is done for', runnerResult.lhr.finalUrl);
console.log('PWA score was', runnerResult.lhr.categories.pwa.score * 100);
await chrome.kill();
})();
Web Vitals is a library for measuring essential metrics that are critical to delivering a great user experience on the web. It focuses on metrics like Largest Contentful Paint (LCP), First Input Delay (FID), and Cumulative Layout Shift (CLS). Unlike Lighthouse, which provides a comprehensive audit, Web Vitals focuses specifically on user-centric performance metrics.
Axe-core is a JavaScript library that helps developers find and fix accessibility issues in their web applications. It is highly focused on accessibility audits, whereas Lighthouse provides a broader range of audits including performance, SEO, and PWA.
PSI (PageSpeed Insights) is a tool that provides insights into how well a page performs on both mobile and desktop devices. It uses Lighthouse under the hood but is more focused on providing actionable insights for performance improvements. PSI is more user-friendly and less customizable compared to running Lighthouse directly.
Lighthouse analyzes web apps and web pages, collecting modern performance metrics and insights on developer best practices.
Lighthouse requires Chrome 56 or later.
Install from the Chrome Web Store
Requires Node v6+.
npm install -g lighthouse
# or use yarn:
# yarn global add lighthouse
Check out the quick-start guide: http://bit.ly/lighthouse-quickstart
Kick off a run by passing lighthouse
the URL to audit:
lighthouse https://airhorner.com/
By default, Lighthouse writes the report to an HTML file. You can control the output format by passing flags.
$ lighthouse --help
lighthouse <url>
Logging:
--verbose Displays verbose logging [boolean]
--quiet Displays no progress or debug logs [boolean]
Configuration:
--disable-device-emulation Disable device emulation [boolean]
--disable-cpu-throttling Disable cpu throttling [boolean]
--disable-network-throttling Disable network throttling [boolean]
--save-assets Save the trace contents & screenshots to disk [boolean]
--save-artifacts Save all gathered artifacts to disk [boolean]
--list-all-audits Prints a list of all available audits and exits [boolean]
--list-trace-categories Prints a list of all required trace categories and exits [boolean]
--config-path The path to the config JSON.
--perf Use a performance-test-only configuration [boolean]
--port The port to use for the debugging protocol. Use 0 for a
random port. [default: 9222]
--max-wait-for-load The timeout (in milliseconds) to wait before the page is
considered done loading and the run should continue.
WARNING: Very high values can lead to large traces and
instability. [default: 25000]
Output:
--output Reporter for the results, supports multiple values
[choices: "json", "html"] [default: "html"]
--output-path The file path to output the results. Use 'stdout' to write to
stdout.
If using JSON output, default is stdout.
If using HTML output, default is a file in the working
directory with a name based on the test URL and date.
If using multiple outputs, --output-path is ignored.
Example: --output-path=./lighthouse-results.html [default: "stdout"]
Options:
--help Show help [boolean]
--version Show version number [boolean]
--skip-autolaunch Skip autolaunch of Chrome when accessing port 9222 fails [boolean]
--select-chrome Interactively choose version of Chrome to use when multiple
installations are found [boolean]
lighthouse
generates
./<HOST>_<DATE>.report.html
lighthouse --output json
generates
stdout
lighthouse --output html --output-path ./report.html
generates
./report.html
NOTE: specifying an output path with multiple formats ignores your specified extension for ALL formats
lighthouse --output json --output html --output-path ./myfile.json
generates
./myfile.report.json
./myfile.report.html
lighthouse --output json --output html
generates
./<HOST>_<DATE>.report.json
./<HOST>_<DATE>.report.html
lighthouse --output-path=~/mydir/foo.out --save-assets
generates
~/mydir/foo.report.html
~/mydir/foo-0.trace.json
~/mydir/foo-0.screenshots.html
lighthouse --output-path=./report.json --output json --save-artifacts
generates
./report.json
./report.artifacts.log
lighthouse --save-artifacts
generates
./<HOST>_<DATE>.report.html
./<HOST>_<DATE>.artifacts.log
chrome-debug
lighthouse http://mysite.com
Lighthouse can run against a real mobile device. You can follow the Remote Debugging on Android (Legacy Workflow) up through step 3.3, but the TL;DR is install & run adb, enable USB debugging, then port forward 9222 from the device to the machine with Lighthouse.
You'll likely want to use the CLI flags --disable-device-emulation --disable-cpu-throttling
and potentially --disable-network-throttling
.
$ adb kill-server
$ adb devices -l
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
00a2fd8b1e631fcb device usb:335682009X product:bullhead model:Nexus_5X device:bullhead
$ adb forward tcp:9222 localabstract:chrome_devtools_remote
$ lighthouse --disable-device-emulation --disable-cpu-throttling https://mysite.com
The example below shows how to setup and run Lighthouse programmatically as a Node module. It
assumes you've installed Lighthouse as a dependency (yarn add --dev lighthouse
).
const lighthouse = require('lighthouse');
const ChromeLauncher = require('lighthouse/lighthouse-cli/chrome-launcher.js').ChromeLauncher;
const Printer = require('lighthouse/lighthouse-cli/printer');
function launchChromeAndRunLighthouse(url, flags, config) {
const launcher = new ChromeLauncher({port: 9222, autoSelectChrome: true});
return launcher.run() // Launch Chrome.
.then(() => lighthouse(url, flags, config)) // Run Lighthouse.
.then(results => launcher.kill().then(() => results)) // Kill Chrome and return results.
.catch(err => {
// Kill Chrome if there's an error.
return launcher.kill().then(() => {
throw err;
});
});
}
// Use an existing config or create a custom one.
const config = require('lighthouse/lighthouse-core/config/perf.json');
const url = 'https://example.com';
const flags = {output: 'html'};
launchChromeAndRunLighthouse(url, flags, config).then(lighthouseResults => {
lighthouseResults.artifacts = undefined; // You can save the artifacts separately if so desired
return Printer.write(lighthouseResults, flags.output);
}).catch(err => console.error(err));
Example - extracting an overall score from all scored audits
function getOverallScore(lighthouseResults) {
const scoredAggregations = lighthouseResults.aggregations.filter(a => a.scored);
const total = scoredAggregations.reduce((sum, aggregation) => sum + aggregation.total, 0);
return (total / scoredAggregations.length) * 100;
}
Helpful for CI integration
Lighthouse can produce a report as JSON, HTML, or stdout CLI output.
HTML report:
Default CLI output:
Running Lighthouse with the --output=json
flag generates a json dump of the run.
You can view this report online by visiting https://googlechrome.github.io/lighthouse/viewer/
and dragging the file onto the app. You can also use the "Export" button from the
top of any Lighthouse HTML report and open the report in the
Lighthouse Viewer.
In the Viewer, reports can be shared by clicking the share icon in the top right corner and signing in to GitHub.
Note: shared reports are stashed as a secret Gist in GitHub, under your account.
# yarn should be installed, first
git clone https://github.com/GoogleChrome/lighthouse
cd lighthouse
yarn install-all
yarn build-all
# The CLI is authored in TypeScript and requires compilation.
# If you need to make changes to the CLI, run the TS compiler in watch mode:
# cd lighthouse-cli && yarn dev
See Contributing for more information.
node lighthouse-cli http://example.com
Getting started tip:
node --inspect --debug-brk lighthouse-cli http://example.com
to open up Chrome DevTools and step through the entire app. See Debugging Node.js with Chrome DevTools for more info.
The audits and gatherers checked into the lighthouse repo are available to any configuration. If you're interested in writing your own audits or gatherers, you can use them with Lighthouse without necessarily contributing upstream.
Better docs coming soon, but in the meantime look at PR #593, and the tests valid-custom-audit.js and valid-custom-gatherer.js. If you have questions, please file an issue and we'll help out!
Tip: see Lighthouse Architecture for more information on Audits and Gatherers.
You can supply your own run configuration to customize what audits you want details on. Copy the default.js and start customizing. Then provide to the CLI with lighthouse --config-path=myconfig.js <url>
If you are simply adding additional audits/gatherers or tweaking flags, you can extend the default configuration without having to copy the default and maintain it. Passes with the same name will be merged together, all other arrays will be concatenated, and primitive values will override the defaults. See the example below that adds a custom gatherer to the default pass and an audit.
{
"extends": true,
"passes": [
{
"passName": "defaultPass",
"gatherers": ["path/to/custom/gatherer.js"]
}
],
"audits": ["path/to/custom/audit.js"],
"aggregations": [
{
"name": "Custom Section",
"description": "Enter description here.",
"scored": false,
"categorizable": false,
"items": [
{
"name": "My Custom Audits",
"audits": {
"name-of-custom-audit": {}
}
}
]
}
]
}
Some basic unit tests forked are in /test
and run via mocha. eslint is also checked for style violations.
# lint and test all files
yarn test
# watch for file changes and run tests
# Requires http://entrproject.org : brew install entr
yarn watch
## run linting and unit tests separately
yarn lint
yarn unit
## run closure compiler (on whitelisted files)
yarn closure
## import your report renderer into devtools-frontend and run devtools closure compiler
yarn compile-devtools
Lighthouse can be used to analyze trace and performance data collected from other tools (like WebPageTest and ChromeDriver). The traces
and devtoolsLogs
artifact items can be provided using a string for the absolute path on disk. The devtoolsLogs array is captured from the Network domain (a la ChromeDriver's enableNetwork
option) and reformatted slightly. As an example, here's a trace-only run that's reporting on user timings and critical request chains:
config.json
{
"audits": [
"user-timings",
"critical-request-chains"
],
"artifacts": {
"traces": {
"defaultPass": "/User/me/lighthouse/lighthouse-core/test/fixtures/traces/trace-user-timings.json"
},
"devtoolsLogs": {
"defaultPass": "/User/me/lighthouse/lighthouse-core/test/fixtures/traces/perflog.json"
}
},
"aggregations": [{
"name": "Performance Metrics",
"description": "These encapsulate your app's performance.",
"scored": false,
"categorizable": false,
"items": [{
"audits": {
"user-timings": { "expectedValue": 0, "weight": 1 },
"critical-request-chains": { "expectedValue": 0, "weight": 1}
}
}]
}]
}
Then, run with: lighthouse --config-path=config.json http://www.random.url
The traceviewer-based trace processor from node-big-rig was forked into Lighthouse. Additionally, the DevTools' Timeline Model is available as well. There may be advantages for using one model over another.
Do Better Web is an initiative within Lighthouse to help web developers modernize their existing web applications. By running a set of tests, developers can discover new web platform APIs, become aware of performance pitfalls, and learn (newer) best practices. In other words, do better on the web!
DBW is implemented as a set of standalone gatherers and audits that are run alongside the core Lighthouse tests. The tests show up under "Best Practices" in the report.
If you'd like to contribute, check the list of issues or propose a new audit by filing an issue.
Nope. Lighthouse runs locally, auditing a page using a local version of the Chrome browser installed the machine. Report results are never processed or beaconed to a remote server.
Lighthouse, ˈlītˌhous (n): a tower or other structure tool containing a beacon light
to warn or guide ships at sea developers.
FAQs
Automated auditing, performance metrics, and best practices for the web.
The npm package lighthouse receives a total of 402,091 weekly downloads. As such, lighthouse popularity was classified as popular.
We found that lighthouse demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 4 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
Security News
Research
A supply chain attack on Rspack's npm packages injected cryptomining malware, potentially impacting thousands of developers.
Research
Security News
Socket researchers discovered a malware campaign on npm delivering the Skuld infostealer via typosquatted packages, exposing sensitive data.