Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Use Google’s PageSpeed Insights runPagespeed endpoint to run Lighthouse for a URL, request the categories and device strategies you care about, then save the raw audits together with the timestamp and configuration. Treat the returned score as a lab diagnostic—not a direct measure of every visitor’s experience—and compare representative repeated runs with field data when available.

What the Lighthouse API actually returns

PageSpeed Insights (PSI) exposes Lighthouse through the runPagespeed REST method. A request must include a page URL. You can optionally specify one or more categories, a locale, and a strategy. The response contains structured Lighthouse data rather than just a number: category scores, individual audit records, metric values, the requested and final URLs, timing, environment and configuration details, warnings, and any runtimeError.

That structure is the useful part for automation. A score is a weighted summary; the audit records explain what caused it and what to investigate.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Design an audit that can be compared later

Make the test context explicit

Run mobile and desktop as separate, labeled requests when both views matter. The emulated form factor changes the test context, so combining the results into one unexplained score makes trend analysis ambiguous. Store the exact strategy, requested categories, locale, timestamp, Lighthouse environment and configuration beside the result.

Request only the categories in scope

If you omit category, the REST reference says PSI runs Performance by default. Ask explicitly for accessibility, best-practices and seo when those questions belong in the audit. Explicit parameters also make a scheduled job self-documenting.

Question Useful request choice What to retain
How fast is the page in a controlled run? category=performance Category score, metric audits and configuration
Does the mobile experience differ? strategy=mobile Strategy, environment and all audit details
How does desktop compare? strategy=desktop A separate run, not a merged score
Are non-performance checks required? Repeat with each required category Category scores and failed audit explanations

Run Lighthouse through the API

cURL

Replace the URL and, if your PSI quota requires it, add your API key according to your Google Cloud setup. The endpoint returns JSON, so save it as an artifact.

curl -G "https://pagespeedonline.googleapis.com/pagespeedonline/v5/runPagespeed" 
  --data-urlencode "url=https://example.com" 
  --data-urlencode "strategy=mobile" 
  --data-urlencode "category=performance" 
  --data-urlencode "category=accessibility" 
  -o lighthouse-mobile.json

Run a second request with strategy=desktop if desktop is part of the question. Keep the filenames or metadata unambiguous.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Python

import json
from datetime import datetime, timezone
import requests

endpoint = "https://pagespeedonline.googleapis.com/pagespeedonline/v5/runPagespeed"
params = [
    ("url", "https://example.com"),
    ("strategy", "mobile"),
    ("category", "performance"),
    ("category", "accessibility"),
]
response = requests.get(endpoint, params=params, timeout=90)
response.raise_for_status()
data = response.json()

record = {
    "fetched_at": datetime.now(timezone.utc).isoformat(),
    "strategy": "mobile",
    "categories": ["performance", "accessibility"],
    "result": data,
}
with open("lighthouse-mobile.json", "w", encoding="utf-8") as f:
    json.dump(record, f, indent=2)

error = data.get("runtimeError")
if error:
    print("Lighthouse runtime error:", error)

Node.js

const endpoint = 'https://pagespeedonline.googleapis.com/pagespeedonline/v5/runPagespeed';
const params = new URLSearchParams({
  url: 'https://example.com',
  strategy: 'mobile',
  category: 'performance',
  locale: 'en-US'
});

const res = await fetch(`${endpoint}?${params}`);
if (!res.ok) throw new Error(`PSI request failed: ${res.status} ${await res.text()}`);
const data = await res.json();

const record = {
  fetched_at: new Date().toISOString(),
  strategy: 'mobile',
  categories: ['performance'],
  result: data
};
console.log(JSON.stringify(record, null, 2));

For repeated categories in JavaScript, construct the query with params.append('category', 'seo') for each additional category; a single key-value object cannot represent duplicate keys reliably.

Parse the response into actionable evidence

Save the complete envelope

Do not keep only performanceScore. Preserve the Lighthouse result, audit map, category references, requested URL, final URL, fetch timestamp, environment, configuration, timing, warnings and runtimeError. The final URL matters when redirects, localization or authentication send the test somewhere other than the input URL.

Read scores and audits separately

Category scores summarize weighted audits. Use them as a headline for a run, then inspect failed audits and their numeric details. Audit records include descriptions, explanations and metric values; those fields form the work list for developers. Follow the audit’s linked documentation before changing code, because a failing audit can be a symptom of a deeper loading or rendering issue.

const audits = data.lighthouseResult?.audits ?? {};
for (const [id, audit] of Object.entries(audits)) {
  if (audit.score !== null && audit.score < 1) {
    console.log({ id, title: audit.title, score: audit.score,
      displayValue: audit.displayValue, explanation: audit.explanation });
  }
}

Metrics worth storing and comparing

PSI and Lighthouse expose metrics including First Contentful Paint (FCP), Largest Contentful Paint (LCP), Speed Index, Cumulative Layout Shift (CLS), Time to Interactive (TTI) and Total Blocking Time (TBT). Save the audit’s numeric value and display value, not just a pass/fail flag. A later Lighthouse version or a changed configuration can alter scoring, so a trend is meaningful only when its context is recorded.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • FCP: when the first content is painted.
  • LCP: when the largest important content element is rendered.
  • Speed Index: how quickly visible content appears during loading.
  • CLS: unexpected layout movement.
  • TTI and TBT: indicators of main-thread blocking and interaction readiness in the lab model.

Choose a small, stable set for dashboards, but retain the full audit map for diagnosis. If a page template changes, record that deployment alongside the run so a score change can be attributed to code rather than an untracked test change.

Lab results versus real-user experience

Lighthouse is a controlled lab test useful for repeatable debugging. PageSpeed Insights can also provide Chrome User Experience Report (CrUX) field data. Field data reflects actual devices, networks, locations, caching and traffic composition, so it can disagree with a lab run. Neither view replaces the other: use lab audits to identify likely causes and field metrics to check whether visitors experience the problem.

When reporting a result, label it as lab or field, include mobile or desktop context, and state the collection period represented by field data. Do not present a single Lighthouse score as a universal percentage of users who are satisfied.

Make recurring audits reliable

Use repeated runs, not a single sample

Network timing, CPU contention, cache state and third-party behavior introduce noise. Schedule several runs and compare a representative median rather than reacting to one unusually good or bad sample. Keep the same URL, strategy, categories and configuration for the comparison set.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose PSI or Lighthouse CI deliberately

PSI is convenient when a job needs an HTTP request and a JSON response. Lighthouse CI is suited to repeatable checks in a build pipeline, running locally or as part of CI. Whichever route you choose, archive the raw result and fail a build only on thresholds your team has defined and tested against normal variation.

Track schema and environment changes

Store the fetch timestamp and the configuration embedded in the response. Lighthouse scoring and audit definitions evolve; a historical score without its version and environment can look like a regression when it is actually a test change.

Troubleshooting common failures

HTTP 400 or a malformed request

Check that url is present, fully qualified and URL-encoded. In cURL, use --data-urlencode; in code, let the query-string library encode it. Verify that repeated category parameters were appended rather than overwritten.

A response contains runtimeError

Treat this as a failed audit, not as a zero score. Log the error object, requested and final URLs, and the configuration. Retry only after checking whether the page is reachable, redirects correctly and can render without an interstitial or authentication wall.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Mobile and desktop results look contradictory

They are different test contexts. Confirm that each stored record labels strategy, then compare the relevant metrics within the same strategy before drawing a conclusion.

Scores jump between runs

Inspect timing, warnings, cache behavior, third-party requests and CPU or network variability. Increase the number of samples, compare medians, and avoid changing code and test configuration in the same experiment.

The score is good but users report slowness

Check CrUX field data and segment by the affected device or geography when that data is available. A lab run may not reproduce a visitor’s network, hardware, cache state or traffic path.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server. It is useful when an audit workflow also needs a clean visual capture: it accepts cookie or consent banners as a visitor and removes more than 60 known consent platforms, newsletter popups and chat widgets before capture. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed, and the response identifies the page verdict and billing status in headers.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

One GET request returns PNG, JPEG, WebP or PDF. The API supports full-page and element captures, device presets, custom viewports, retina scale, dark mode, waits, request blocking, headers, cookies, user agents, timezone and geolocation, custom CSS or JavaScript, resizing, caching, signed links, asynchronous jobs, webhooks, bulk capture and a usage API. Its MCP server exposes take_screenshot, get_page_info and capture_pdf to Claude, Cursor and other MCP clients.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for parameters and response headers. The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. Sign up free to try it.

A practical storage and review checklist

  • Record the URL submitted and the final URL reached.
  • Store ISO-8601 fetch time, strategy, locale, requested categories and Lighthouse configuration.
  • Archive the complete JSON, including warnings and runtimeError.
  • Save metric values, display values, audit explanations and links.
  • Compare repeated runs with a median and annotate deployments.
  • Read lab and CrUX field data as complementary evidence.
  • Set thresholds only after observing normal variance.

FAQ

Does the API require an API key?

The endpoint and your Google Cloud or PSI quota configuration determine whether a key is needed. Keep credentials out of source control and follow the quota guidance for your account.

Can one request test both mobile and desktop?

No. Use separate requests with explicitly labeled strategy=mobile and strategy=desktop values so the results remain comparable.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Should I alert on a category score alone?

No. Alerting should point to the underlying audit and metric evidence, while allowing for normal run-to-run variability.

Frequently Asked Questions

Does the API require an API key?

The endpoint and your Google Cloud or PSI quota configuration determine whether a key is needed. Keep credentials out of source control and follow the quota guidance for your account.

Can one request test both mobile and desktop?

No. Use separate requests with explicitly labeled strategy=mobile and strategy=desktop values so the results remain comparable.

Should I alert on a category score alone?

No. Alerting should point to the underlying audit and metric evidence, while allowing for normal run-to-run variability.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.