Article

Scheduled Lighthouse scans with Unlighthouse, Cloud Run and Datadog

Run Unlighthouse as a scheduled Cloud Run job, send Lighthouse scores to Datadog in batches and alert on a score drop for each page.

Published Updated 8 min read

This guide builds a scanner that runs Lighthouse on a fixed list of pages every few hours, as a Cloud Run job that Cloud Scheduler starts. The scores and metrics go to Datadog, so you can see trends over months and alert on a drop, while the full reports go to a Cloud Storage bucket. The guide is for frontend engineers and tech leads who own web performance. The examples use unlighthouse 0.20.0, which runs lighthouse 13.6.0 through @unlighthouse/core 0.20.0, the current npm versions on 1 December 2026.

Why Unlighthouse and not k6 or sitespeed.io

Unlighthouse runs Lighthouse on many pages in one process, with several pages in parallel, and writes a standard Lighthouse report (LHR) for each page. You get all four Lighthouse categories: performance, accessibility, best practices and SEO.

k6 is a load testing tool whose HTTP requests do not render a page, so on a site behind a CDN they mostly test the cache. The k6 browser module adds browser automation and collects Web Vitals such as browser_web_vital_lcp and browser_web_vital_cls, but it does not run Lighthouse, so you get no category scores.

sitespeed.io is built on Browsertime and runs Lighthouse through a plugin, after the Browsertime run. It sends its metrics to Graphite or InfluxDB, so it fits well if you already run that stack.

If you need Lighthouse scores for many pages in Datadog, Unlighthouse is the smallest step.

The Docker image

Unlighthouse uses puppeteer-core, which does not bundle a browser, so install Chromium from Debian and point Unlighthouse to it. @unlighthouse/core 0.20.0 needs Node.js 22.18 or later.

FROM node:24-trixie-slim

RUN apt-get update \
  && apt-get install -y --no-install-recommends chromium \
  && rm -rf /var/lib/apt/lists/*

ENV CHROME_PATH=/usr/bin/chromium

WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY . .
RUN chown -R node:node /app

USER node
CMD ["node", "scan.mjs"]

Add unlighthouse to dependencies, not to devDependencies, because the image installs without dev packages. The node user must own /app, because Unlighthouse writes its output to .unlighthouse in the working directory.

The Unlighthouse config

Unlighthouse loads unlighthouse.config.ts from the working directory. The device comes from an environment variable, so one image serves mobile and desktop.

import { defineUnlighthouseConfig } from 'unlighthouse/config'

export default defineUnlighthouseConfig({
  scanner: {
    device: process.env.SCAN_DEVICE === 'desktop' ? 'desktop' : 'mobile',
    samples: 1,
    ignoreI18nPages: false,
  },
  puppeteerOptions: {
    executablePath: process.env.CHROME_PATH,
    args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-gpu'],
  },
  puppeteerClusterOptions: {
    maxConcurrency: 2,
  },
})

The options do the following:

  • scanner.device is mobile by default, and the desktop preset uses a 1350 × 940 viewport.
  • scanner.samples is the number of Lighthouse runs per page, with a default of 1. More samples give a steadier score, but the scan takes longer.
  • scanner.ignoreI18nPages is true by default, which makes Unlighthouse skip a page that has an hreflang="x-default" link to another URL and scan that other URL instead. Set it to false when you want every locale.
  • puppeteerOptions.executablePath makes Unlighthouse use the Debian Chromium.
  • The args come from the Unlighthouse Docker guide, which is community-maintained.
  • puppeteerClusterOptions.maxConcurrency sets the number of parallel pages, and the Unlighthouse docs suggest 1 for the most accurate scores. A higher value is faster but adds CPU contention, so pick a value and keep it.

Unlighthouse throttles remote sites by default, with a preset of 150 ms round-trip time and 1,638.4 Kbps and no CPU slowdown. The mobile default of Lighthouse itself uses the same network values with a 4x CPU slowdown, so your scores will differ from PageSpeed Insights. That is fine for trends, as long as the settings stay the same between runs.

The page list

Keep the pages in a JSON file, with a page type that becomes a tag in Datadog.

[
  { "path": "/en-gb/", "pageType": "home" },
  { "path": "/en-gb/bath-and-body/", "pageType": "category" },
  { "path": "/en-gb/hand-wash-250ml/", "pageType": "product" },
  { "path": "/nl-nl/", "pageType": "home" }
]

When you pass explicit URLs, Unlighthouse does not read the sitemap or robots.txt and does not crawl. The paths are relative to --site, so use one job per site.

The scan script

The script runs Unlighthouse in batches of 25 pages. After each batch, it reads the reports, sends the metrics to Datadog and copies the reports to the bucket.

import { execFileSync } from 'node:child_process'
import { cp, readdir, readFile } from 'node:fs/promises'
import { join } from 'node:path'

const SITE = process.env.SCAN_SITE // https://www.example.com
const SITE_TAG = process.env.SITE_TAG // legacy or new
const DEVICE = process.env.SCAN_DEVICE ?? 'mobile'
const DD_SITE = process.env.DD_SITE ?? 'datadoghq.eu'
const REPORTS_DIR = '/mnt/reports'
const BATCH_SIZE = 25
const RUN_ID = new Date().toISOString().replace(/[:.]/g, '-')

const pages = JSON.parse(await readFile('pages.json', 'utf8'))
const pageTypes = new Map(pages.map((page) => [page.path, page.pageType]))

async function readReports() {
  const dir = join('.unlighthouse', 'reports')
  const files = await readdir(dir, { recursive: true })
  const reports = []
  for (const file of files.filter((f) => f.endsWith('lighthouse.json'))) {
    reports.push(JSON.parse(await readFile(join(dir, file), 'utf8')))
  }
  return reports
}

function toSeries(lhr) {
  const path = new URL(lhr.requestedUrl).pathname
  const timestamp = Math.floor(Date.parse(lhr.fetchTime) / 1000)
  const tags = [
    `site:${SITE_TAG}`,
    `device:${DEVICE}`,
    `locale:${path.split('/')[1] || 'none'}`,
    `page_type:${pageTypes.get(path) ?? 'other'}`,
    `page_path:${path}`,
  ]
  const scores = {
    performance: lhr.categories.performance?.score,
    accessibility: lhr.categories.accessibility?.score,
    best_practices: lhr.categories['best-practices']?.score,
    seo: lhr.categories.seo?.score,
  }
  const values = {
    ...Object.fromEntries(
      Object.entries(scores).map(([key, score]) => [`lighthouse.score.${key}`, score == null ? null : score * 100]),
    ),
    'lighthouse.lcp_ms': lhr.audits['largest-contentful-paint']?.numericValue,
    'lighthouse.cls': lhr.audits['cumulative-layout-shift']?.numericValue,
    'lighthouse.tbt_ms': lhr.audits['total-blocking-time']?.numericValue,
    'lighthouse.speed_index_ms': lhr.audits['speed-index']?.numericValue,
  }
  return Object.entries(values)
    .filter(([, value]) => typeof value === 'number')
    .map(([metric, value]) => ({ metric, type: 3, points: [{ timestamp, value }], tags }))
}

async function sendSeries(series) {
  for (let i = 0; i < series.length; i += 500) {
    const res = await fetch(`https://api.${DD_SITE}/api/v2/series`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'DD-API-KEY': process.env.DD_API_KEY },
      body: JSON.stringify({ series: series.slice(i, i + 500) }),
    })
    if (res.status !== 202) throw new Error(`Datadog returned ${res.status}: ${await res.text()}`)
  }
}

let failedBatches = 0
for (let i = 0; i < pages.length; i += BATCH_SIZE) {
  const batch = i / BATCH_SIZE + 1
  const paths = pages.slice(i, i + BATCH_SIZE).map((page) => page.path)
  try {
    execFileSync('npx', ['unlighthouse-ci', '--site', SITE, '--urls', paths.join(',')], { stdio: 'inherit' })
    const reports = (await readReports()).filter((lhr) => !lhr.runtimeError)
    await sendSeries(reports.flatMap(toSeries))
    await cp(join('.unlighthouse', 'reports'), join(REPORTS_DIR, RUN_ID, DEVICE, `batch-${batch}`), { recursive: true })
  } catch (error) {
    failedBatches++
    console.error(`Batch ${batch} failed`, error)
  }
}
if (failedBatches > 0) process.exitCode = 1

Some details:

  • In CI mode, Unlighthouse turns off its cache and clears .unlighthouse before each run, so each batch starts empty. Unlighthouse refuses to clear a folder that it did not create, so do not point its output at the bucket mount, and copy the reports there afterwards instead.
  • Each page gets lighthouse.json (the LHR) and lighthouse.html in its own folder under reports.
  • Category scores in the LHR run from 0 to 1, so the script multiplies them by 100. A score can be null when a run fails, and the filter drops those values.
  • The --reporter jsonExpanded output has no Speed Index, which is why the script reads the LHR files.

Why batches

Batches solve three problems:

  • Datadog accepts points with a timestamp up to 1 hour in the past, and the script uses the Lighthouse fetchTime. If you send everything at the end of a long scan, early points can be too old.
  • The filesystem of a Cloud Run container is in memory, so the reports use instance memory and small batches keep that usage low.
  • One failed batch does not lose the whole run.

The Datadog payload

The v2 series endpoint takes a list of series, where type: 3 is a gauge and timestamps are in seconds. A successful request returns 202, and the compressed payload can be at most 500 KB. One batch of 25 pages gives 200 series, so it fits in one request.

Datadog lowercases tags and turns unsupported characters into underscores. Slashes, colons, periods and minus signs are allowed, so page_path:/en-gb/ stays readable.

Deploy the job

Build the image in CI and push it to Artifact Registry, then deploy one job per site and device:

gcloud run jobs deploy lighthouse-scan-legacy-mobile \
  --image=europe-west1-docker.pkg.dev/PROJECT_ID/scans/lighthouse-scan:latest \
  --region=europe-west1 \
  --tasks=1 \
  --max-retries=0 \
  --task-timeout=30m \
  --cpu=2 \
  --memory=4Gi \
  --set-env-vars=SCAN_SITE=https://www.example.com,SITE_TAG=legacy,SCAN_DEVICE=mobile,DD_SITE=datadoghq.eu \
  --set-secrets=DD_API_KEY=datadog-api-key:latest \
  --add-volume=name=reports,type=cloud-storage,bucket=example-lighthouse-reports \
  --add-volume-mount=volume=reports,mount-path=/mnt/reports \
  --service-account=lighthouse-scan@PROJECT_ID.iam.gserviceaccount.com

Notes on the flags:

  • The default task timeout is 10 minutes, and a scan of 100 pages needs more.
  • --max-retries=0 does not rerun a failed scan, since the next scheduled run follows within 4 hours.
  • --set-secrets reads the Datadog API key from Secret Manager.
  • The bucket mount uses Cloud Storage FUSE, which has no file locking and is not fully POSIX, so a new folder per run avoids conflicts.
  • The service account needs the Storage Object User role on the bucket.

Schedule the job

Cloud Scheduler calls the Cloud Run Admin API to run the job, and this example runs every 4 hours:

gcloud scheduler jobs create http lighthouse-scan-legacy-mobile-every-4h \
  --location=europe-west1 \
  --schedule="0 */4 * * *" \
  --time-zone="Etc/UTC" \
  --uri="https://run.googleapis.com/v2/projects/PROJECT_ID/locations/europe-west1/jobs/lighthouse-scan-legacy-mobile:run" \
  --http-method=POST \
  --oauth-service-account-email=scan-scheduler@PROJECT_ID.iam.gserviceaccount.com

The scheduler’s service account needs the Cloud Run Invoker role.

Alert on a score drop

A change monitor compares the recent average with the same window one day earlier:

change(avg(last_8h),1d_ago):avg:lighthouse.score.performance{device:mobile} by {site,page_path} < -15

The monitor creates one alert per site and page. Keep require_full_window off, because the scan sends one point every 4 hours, and put the page link in the message:

{{#is_alert}}
Performance score of {{page_path.name}} on {{site.name}} changed by {{value}} points.
Open the page: https://www.example.com{{page_path.name}}
{{/is_alert}}

Datadog lowercases tag values, so the link can break if your paths contain capitals. Keep the paths in pages.json lowercase.

Cost and runtime

Datadog counts a custom metric for each unique combination of metric name and tag values. Sending a point more often does not create a new custom metric, but a new tag value does.

An example: 200 page paths, 2 devices and 2 sites give up to 800 tag combinations per metric, and because the locale and page type follow from the path, they add no combinations. With 8 metric names, that is up to 6,400 custom metrics, so check this against the allotment in your plan before you add pages.

Cloud Run bills a job for the whole lifetime of its instance, with a minimum of 1 minute. Runtime grows with the number of pages and falls with concurrency. For example, if one page takes 20 seconds and 2 pages run in parallel, 100 pages take about 1,000 seconds, which is about 17 minutes. Measure one batch and set the task timeout with a margin.

In practice

In January 2026, we built this kind of scanner for an international cosmetics retailer that is moving from Salesforce Commerce Cloud to a headless Next.js platform, market by market. The teams needed to compare the legacy storefront with the new storefront page by page, while a single Lighthouse report shows only one moment.

Unlighthouse was chosen over k6, and sitespeed.io was also tested. A static HTML report was dropped, so the data goes only to Datadog. The scanner runs in a Docker container as a Cloud Run job and sends its results to Datadog in batches with a device tag: the four category scores, LCP, CLS, TBT and Speed Index. The full reports go to a storage bucket.

The client’s DevOps engineer built the deploy pipeline: GitHub Actions builds the image, and Cloud Scheduler starts the job. Every 4 hours, the scanner tests about 100 top pages in 4 main markets on mobile and desktop, on both storefronts. A Datadog monitor alerts when performance drops, and the alert links to the page. In the first quarter of 2026, a dashboard with the scores was used in sessions with the legacy team. In May 2026, the scan grew to all consumer locales and more page templates. A view shows the pages with the lowest scores, and you can read more in the case study.

Checklist

  • Install Chromium in the image and set puppeteerOptions.executablePath.
  • Set scanner.ignoreI18nPages: false for a site with many locales.
  • Keep device, throttling, samples and concurrency the same between runs.
  • Use one job per site and device.
  • Send metrics after each batch, within the 1-hour timestamp window.
  • Tag by site, device, locale, page type and page path.
  • Check for a 202 response from Datadog.
  • Copy reports to a new bucket folder per run.
  • Raise the task timeout above the 10-minute default.
  • Alert on a change, not on an absolute score.
  • Count your tag combinations before you add pages.

For a review of your web performance monitoring, see the frontend observability assessment or contact us.

Sources

Let's connect

Talk about your project

Tell us about your team and your problem. In 30 minutes we find out whether one of our offers fits, and if none does, we tell you.

Book a 30-minute call