Unlighthouse Documentation

repository·main·Indexed 26 days ago

https://github.com/harlan-zw/unlighthouse

Unlighthouse is a tool that scans entire websites using Google Lighthouse, featuring a modern UI, minimal configuration, and smart sampling to analyze site performance and quality. It includes a CLI for scanning, a Vue-based interactive dashboard (@unlighthouse/client), and a CI tool (unlighthouse-ci) for enforcing performance budgets in automated workflows. The tool supports custom configurations via unlighthouse.config.ts, programmatic integration via createUnlighthouse(), and historical data retrieval using the CrUX API.

Tokens
38.9K
Snippets
153
Records
229
Agent score
89%

What's inside Unlighthouse

  1. Understand Core Web Vitals

    main

    Core Web Vitals are Google's key metrics for user experience and serve as a direct ranking factor in search results. The three primary metrics are:

    • LCP (Largest Contentful Paint): Measures loading performance by tracking how quickly the main content appears.
    • CLS (Cumulative Layout Shift): Measures visual stability by tracking if content jumps around unexpectedly.
    • INP (Interaction to Next Paint): Measures responsiveness by tracking how quickly the page responds to user clicks.
  2. Understand Total Blocking Time (TBT)

    main

    Total Blocking Time (TBT) measures the total time the main thread was blocked during page load. It is the heaviest-weighted Lighthouse metric (30%) and indicates how responsive a page feels during the loading phase.

    How TBT is calculated

    TBT counts the 'blocking' portion of all Long Tasks (JavaScript tasks running for > 50ms) between First Contentful Paint (FCP) and when the page becomes reliably interactive. Only the duration exceeding 50ms counts toward TBT:

    • Task duration: 70ms → Blocking time: 20ms
    • Task duration: 250ms → Blocking time: 200ms
    • Task duration: 30ms → Blocking time: 0ms

    TBT Score Thresholds

    ScoreRating
    ≤ 200msGood
    200ms - 600msNeeds Improvement
    > 600msPoor

    TBT vs INP

    • TBT: A lab metric measuring main thread blocking during load.
    • INP (Interaction to Next Paint): A field metric measuring actual interaction latency throughout the entire session.
  3. Understand Interaction to Next Paint (INP) metrics

    main

    Interaction to Next Paint (INP) measures page responsiveness by tracking the latency of all clicks, taps, and keyboard interactions throughout a page's lifecycle. It includes input delay, processing time, and presentation delay.

    INP Score Thresholds

    ScoreRating
    ≤ 200msGood
    200ms - 500msNeeds Improvement
    > 500msPoor

    Google recommends an INP of 200ms or less for at least 75% of page visits. Unlike First Input Delay (FID), INP measures all interactions and the full interaction lifecycle, making it a more comprehensive Core Web Vital.

  4. Understand the Unlighthouse scanning workflow

    main

    The scanning process follows these stages:

    1. URL Discovery

    Unlighthouse finds pages via:

    • Route Files: Reading framework-specific route files (e.g., Next.js).
    • Robots.txt: Checking for sitemap links.
    • Sitemap.xml: Extracting URLs from your sitemap (recommended for speed and coverage).
    • Crawling: Following links starting from the homepage if no sitemap is found.

    2. Page Processing

    For every discovered URL, Unlighthouse performs:

    • Quick HTML Check: An HTTP request to grab metadata (title, meta tags) and discover more links.
    • Full Lighthouse Scan: Opening the page in a Chrome instance (via puppeteer-cluster) to run full Lighthouse audits and Core Web Vitals tests, saving results as HTML and JSON.
  5. Explore @unlighthouse/client features

    main

    The @unlighthouse/client provides several features for interacting with Lighthouse scan data:

    • Interactive dashboard: View performance metrics across your site.
    • Real-time tracking: Monitor scan progress as it happens.
    • Detailed reports: Access granular Lighthouse reports for individual pages.
    • Visualizations: View performance charts and data visualizations.
    • Exporting: Utilize export capabilities for your scan data.
  6. Understand Lighthouse Performance Metrics

    main

    Lighthouse reports several additional metrics that contribute to your overall performance score:

    • FCP (First Contentful Paint): When the first content renders.
    • TTFB (Time to First Byte): Server response time.
    • TBT (Total Blocking Time): Measures main thread blocking during load. This accounts for 30% of the Lighthouse score.
    • Speed Index: Measures visual loading progress and how quickly content fills the viewport.
  7. Run unlighthouse-ci with basic budget enforcement

    main

    The unlighthouse-ci command scans your entire site and enforces a performance budget. If any page score falls below the specified threshold, the command exits with code 1 (failing the build). If all pages pass, it exits with code 0.

    # Scan site, fail if any page < 75
    unlighthouse-ci --site example.com --budget 75
    
    # Generate a static HTML report alongside the budget check
    unlighthouse-ci --site example.com --budget 75 --build-static
    unlighthouse-ci --site example.com --budget 75
  8. Measure Speed Index using Unlighthouse

    main

    To measure Speed Index across your entire site, use the Unlighthouse CLI. Note that Speed Index cannot be measured via client-side JavaScript; it requires video capture and frame-by-frame analysis provided by lab tools like Lighthouse.

    For individual page analysis, you can also use:

    • Lighthouse in Chrome DevTools
    • PageSpeed Insights
    • WebPageTest
  9. Run Unlighthouse in desktop mode via CLI

    main

    By default, Unlighthouse uses mobile emulation because of Google's mobile-first indexing. To override this and scan using a desktop viewport, use the --desktop flag. This flag is equivalent to --device desktop and takes precedence over any settings in your configuration file.

    npx unlighthouse --site https://example.com --desktop
  10. Use Puppeteer Navigation Hooks

    main

    You can hook into Puppeteer's page navigation using the hooks configuration. The puppeteer:before-goto hook allows you to execute logic before the browser navigates to a URL.

    Set localStorage before navigation

    Use page.evaluateOnNewDocument within the hook to inject data like authentication tokens into the browser context before the page loads.

    Modify Page Content

    You can use the hook to wait for navigation and then use page.evaluate to manipulate the DOM, such as removing elements (e.g., cookie banners) that might interfere with Lighthouse metrics like CLS.

    // Set localStorage before navigation
    export default defineUnlighthouseConfig({
      hooks: {
        'puppeteer:before-goto': async (page) => {
          await page.evaluateOnNewDocument((token) => {
            localStorage.setItem('auth', token)
          }, process.env.AUTH_TOKEN)
        },
      },
    })
    
    // Remove elements that cause CLS
    export default defineUnlighthouseConfig({
      hooks: {
        'puppeteer:before-goto': async (page) => {
          page.waitForNavigation().then(async () => {
            await page.evaluate(() => {
              document.querySelector('.cookie-banner')?.remove()
            })
          })
        },
      },
    })