Skip to main content

Confirm

Are you sure?

Node.js · Code recipe

Run a Lighthouse audit in Node.js

Score any page for performance, accessibility, best practices and SEO, in Node.js 18+ with the built-in fetch. Every program on this page runs as it stands — each one was run against a stub of the API before it was published.

By · Last updated: September 2026

TL;DR

To run a Lighthouse audit in Node.js, POST a URL and a device to https://urlpipe.dev/lighthouse and read the JSON with await res.json(): four category scores from 0 to 1 and the lab metrics, LCP, CLS and TBT among them. An audit takes around 15 seconds, so the async variant with a webhook suits production. It costs 2 credits.

Free plan, no credit card. 1,000 credits a month.

One POST to /lighthouse runs a real Lighthouse audit in Chrome and answers with the four category scores — performance, accessibility, best practices, SEO — and the lab metrics behind the performance score. device picks mobile (the default, throttled CPU and network) or desktop.

In Node.js the report is read with await res.json(). Scores run from 0 to 1, so the program multiplies by 100 to print what the Lighthouse report shows; metrics carry a ready-formatted displayValue. The guide to reading a Lighthouse audit explains what each number means.

Setup

Before you start

Nothing to install: fetch is global from Node 18. The files end in .mjs so Node reads them as ES modules and top-level await works without a wrapper function.

Terminal
node --version   # v18 or later
export URLPIPE_API_KEY="your_api_key"

The request

Print the four scores, LCP, CLS and TBT

sync: true keeps the request open until the result is ready. fetch resolves on any status, 4xx and 5xx included, so check res.ok yourself. Optional chaining (?.) covers a category or metric Lighthouse could not compute, which arrives as null.

lighthouse_audit.mjs
const res = await fetch("https://urlpipe.dev/lighthouse", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.URLPIPE_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ url: "https://example.com", device: "mobile", sync: true }),
  // fetch has no timeout of its own; a sync call can take up to 60 s.
  signal: AbortSignal.timeout(90_000),
});
if (!res.ok) throw new Error(`URLpipe answered ${res.status}: ${await res.text()}`);

const report = await res.json();
for (const name of ["performance", "accessibility", "best-practices", "seo"]) {
  const score = report.categories[name]?.score;
  console.log(`${name}: ${score == null ? "n/a" : Math.round(score * 100)}`);
}

const metrics = {
  LCP: "largest-contentful-paint",
  CLS: "cumulative-layout-shift",
  TBT: "total-blocking-time",
};
for (const [label, key] of Object.entries(metrics)) {
  console.log(`${label}: ${report.metrics[key]?.displayValue ?? "n/a"}`);
}

Run it: node lighthouse_audit.mjs

Given the example response on the docs page, it prints:

Output
performance: 95
accessibility: 88
best-practices: 92
seo: 90
LCP: 2.5 s
CLS: 0.05
TBT: 150 ms

Async

The async variant: a token, a webhook and a poll

Leave out sync and the answer is a token, straight away. setTimeout from node:timers/promises is the awaitable sleep, so the polling loop reads top to bottom.

lighthouse_audit_async.mjs
import { setTimeout as sleep } from "node:timers/promises";

const API = "https://urlpipe.dev";
const headers = {
  Authorization: `Bearer ${process.env.URLPIPE_API_KEY}`,
  "Content-Type": "application/json",
};

// No sync: the request is accepted at once and the work carries on without you.
const accepted = await fetch(`${API}/lighthouse`, {
  method: "POST",
  headers,
  body: JSON.stringify({
    url: "https://example.com",
    device: "mobile",
    report_to: "https://your-app.com/webhooks/urlpipe",
    labels: { customer: "acme" },
  }),
});
if (!accepted.ok) throw new Error(`URLpipe answered ${accepted.status}: ${await accepted.text()}`);
const { token } = await accepted.json();
console.log(`Accepted ${token}`);

// The result is POSTed to report_to when it is ready. Polling by token is the
// other way to collect it: no endpoint needed, and a backup for the webhook.
let res;
for (let attempt = 0; attempt < 60; attempt++) {
  res = await fetch(`${API}/result/${token}`, { headers });
  if (res.status !== 202) break; // 202 means still processing
  await sleep(2000);
}
if (res.status === 202) throw new Error("Still processing after two minutes; try the token again later.");
if (res.status === 422) throw new Error(`The analysis failed: ${(await res.json()).error}`);
if (res.status === 410) throw new Error("The result is past the 30-day window; send the request again.");
if (!res.ok) throw new Error(`URLpipe answered ${res.status}: ${await res.text()}`);

const report = await res.json();
for (const name of ["performance", "accessibility", "best-practices", "seo"]) {
  const score = report.categories[name]?.score;
  console.log(`${name}: ${score == null ? "n/a" : Math.round(score * 100)}`);
}

const metrics = {
  LCP: "largest-contentful-paint",
  CLS: "cumulative-layout-shift",
  TBT: "total-blocking-time",
};
for (const [label, key] of Object.entries(metrics)) {
  console.log(`${label}: ${report.metrics[key]?.displayValue ?? "n/a"}`);
}

Run it: node lighthouse_audit_async.mjs

Errors

Handle errors and retries

Read the status before the body: a 401 answers in plain text, so res.json() would throw. .catch(() => ({})) turns any body that is not JSON into an empty object, and the status still says what happened.

lighthouse_audit_errors.mjs
import { setTimeout as sleep } from "node:timers/promises";

class URLpipeError extends Error {}

// POST a sync request and return the response, or throw URLpipeError.
async function urlpipe(path, payload, attempts = 5) {
  for (let attempt = 0; attempt < attempts; attempt++) {
    const res = await fetch(`https://urlpipe.dev${path}`, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${process.env.URLPIPE_API_KEY}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ ...payload, sync: true }),
      signal: AbortSignal.timeout(90_000),
    });
    if (res.ok) return res;
    if (res.status === 401) {
      throw new URLpipeError("401: the API key is missing or wrong. Check URLPIPE_API_KEY.");
    }

    const body = await res.json().catch(() => ({}));
    const code = body.error ?? "";
    const detail = body.message ? `${code}: ${body.message}` : code;

    if (res.status === 429 && code === "rate_limited") {
      // Sending too fast: Retry-After says how long the window has left.
      await sleep(Number(res.headers.get("Retry-After") ?? 1) * 1000);
    } else if (res.status === 429 && code === "concurrency_limit") {
      // Every parallel slot on your plan is busy with your own requests.
      await sleep(2 ** attempt * 1000);
    } else if (res.status === 504) {
      // Still running on our side; the token collects it from GET /result/:token.
      throw new URLpipeError(`504 processing_timeout: collect it later with token ${body.token}`);
    } else {
      // 403 email_unverified, 422 (a bad parameter, or a page that would not load),
      // 429 quota_exceeded: sending the same request again gets the same answer.
      throw new URLpipeError(`${res.status}: ${detail}`);
    }
  }
  throw new URLpipeError(`429: still refused after ${attempts} attempts`);
}

let res;
try {
  res = await urlpipe("/lighthouse", { url: "https://example.com", device: "mobile" });
} catch (error) {
  console.error(`URLpipe: ${error.message}`);
  process.exit(1);
}

const report = await res.json();
for (const name of ["performance", "accessibility", "best-practices", "seo"]) {
  const score = report.categories[name]?.score;
  console.log(`${name}: ${score == null ? "n/a" : Math.round(score * 100)}`);
}

const metrics = {
  LCP: "largest-contentful-paint",
  CLS: "cumulative-layout-shift",
  TBT: "total-blocking-time",
};
for (const [label, key] of Object.entries(metrics)) {
  console.log(`${label}: ${report.metrics[key]?.displayValue ?? "n/a"}`);
}

Run it: node lighthouse_audit_errors.mjs

Details

What to know about /lighthouse

  • Lighthouse 13 reports four categories; the pwa key is always null, kept so the shape does not change.
  • The performance score weights TBT 30%, LCP 25%, CLS 25%, FCP 10% and Speed Index 10%.
  • INP needs real users and cannot be measured in a lab run; TBT is its lab stand-in.
  • "include_audits": "true" adds the full list of audits, with the elements to fix. Mobile and desktop are cached separately.
  • Want the audit run on a schedule, with a history and alerts? Full Stack Audit sells that as a monitored report; URLpipe is the primitive underneath.

Other languages

Run a Lighthouse audit in another language

More Node.js: every Node.js recipe

FAQ

Frequently asked questions

Mobile or desktop — which device should I audit?
Mobile, unless you know your traffic is desktop. It emulates a 360×640 phone with a 4× slower CPU and a slow 4G network, which gives the lower, more telling scores. Pass device: "desktop" for a 1350×940 window with no throttling.
Why isn't INP in the results?
INP is measured from real users interacting with the page, which a lab audit cannot do. Total Blocking Time is the lab metric that tracks it.
Why use the async variant for Lighthouse?
An audit takes around 15 seconds, longer on a heavy page. Async hands you a token at once and delivers the report to your webhook, so nothing holds a connection open waiting.
Do I need an SDK to call URLpipe from Node.js?
No package at all: Node 18 and later ship fetch, and the API is one POST per job.

Get a key and run it.

Free plan, no card. Paste your key into URLPIPE_API_KEY and every program on this page runs as it is.