Duong Hoang Nam

Search Articles

Find AI, technology, and programming guides

Press Esc to closeFull Search Page →
Tutorials

How to Prevent Astro Performance Regressions with Lighthouse CI and GitHub Actions (2026 Guide)

Learn how to run Lighthouse CI on Astro with GitHub Actions, set practical performance budgets, save reports, and catch regressions before deployment.

By Duong Hoang Nam
How to Prevent Astro Performance Regressions with Lighthouse CI and GitHub Actions (2026 Guide)

A fast Astro website can become slower without anyone noticing. One new third-party script, an oversized hero image, a font change, or a redesigned consent banner can affect loading and visual stability even when the project builds successfully.

Manually running PageSpeed Insights after every change is useful, but it does not scale well as a publishing process. A better approach is to add a repeatable performance check to your pull requests.

In this tutorial, you’ll set up Lighthouse CI (LHCI) for a static Astro project, audit selected routes, define practical performance budgets, and save reports from GitHub Actions. You’ll also learn what these automated measurements cannot tell you about real visitors.

Scope: This is a reference implementation for a static Astro build. The example has not been executed against the DuongHoangNam.com repository, and the thresholds shown are starting policies rather than measured results.

1. Why Performance Regressions Happen

Performance problems often arrive as small, individually reasonable changes:

  • A large new featured image becomes the Largest Contentful Paint (LCP) element.
  • A third-party analytics or embedded widget increases JavaScript work.
  • Missing image dimensions introduce layout movement.
  • A new font file delays the first meaningful text render.
  • A cookie banner changes the layout after loading.
  • An external dependency changes behavior without a code change.

Astro’s static output is an advantage, but static generation alone does not guarantee a page will remain fast. A new page can pass a build and still deliver unnecessary bytes or create layout shifts.

The goal of performance CI is to detect potential regressions early, not to promise an exact speed for every visitor.

2. How the Lighthouse CI Workflow Fits Together

A practical pull-request workflow looks like this:

  1. A developer or content editor changes the Astro project.
  2. GitHub Actions installs dependencies and runs the production build.
  3. Lighthouse CI starts a local static server for the generated dist/ directory.
  4. It audits representative pages several times.
  5. Assertions print warnings or errors when a budget is exceeded.
  6. The workflow saves HTML and JSON reports for review.
  7. The maintainer compares the results with previous runs before merging.

Lighthouse CI workflow from Astro pull request through build, audits, budget checks, and downloadable reports

Figure 1: A repeatable performance check runs on the built Astro output before deployment.

This process complements, rather than replaces, checking the deployed Cloudflare Pages site. An edge function, CDN configuration, third-party consent system, or production-only dependency may behave differently online.

3. Understand Lab Tests Versus Real User Data

Lighthouse CI uses a controlled browser run, so its results are lab measurements. Core Web Vitals represent experiences gathered from real users in the field.

Metric What it measures Important limitation
LCP When the largest visible content element appears Can vary with image delivery and device speed
CLS Unexpected visual movement A short test may miss shifts after interaction
TBT Main-thread blocking during page load A lab proxy, not Interaction to Next Paint
INP Responsiveness to user interaction Needs field data or deliberate interactive testing
Performance score Lighthouse’s weighted lab score Not a universal SEO score or business KPI

The current Core Web Vitals focus on LCP, CLS, and INP. Google’s commonly recommended good thresholds are LCP at most 2.5 seconds, CLS at most 0.1, and INP at most 200 milliseconds, evaluated at the 75th percentile of eligible field experiences.

You cannot claim that a site passes its field Core Web Vitals simply because a Lighthouse CI job passes. Continue reviewing PageSpeed Insights field data and Search Console when available.

Official reference: web.dev — Web Vitals.

4. Prepare the Astro Project

The example assumes:

  • A static Astro site committed to a GitHub repository.
  • A working npm run build script.
  • A generated dist/ directory (or an explicitly configured alternative).
  • GitHub Actions enabled for the repository.
  • A lockfile committed so npm ci can install repeatable dependencies.

From the project root, verify the build before adding CI:

npm ci
npm run build

Astro writes static output to dist/ by default, but this can be changed in astro.config.*.

If your application uses server-rendered routes, a Cloudflare adapter, or Pages Functions, the static-site example below does not exercise those runtime endpoints. You will need a production-like server or staging deployment for that portion of testing.

5. Install Lighthouse CI

Add the CLI as a development dependency:

npm install --save-dev @lhci/[email protected]

The version series shown here matches the official Lighthouse CI getting-started examples at the time this tutorial was prepared. Check the current release and Node.js compatibility before upgrading.

You can inspect the CLI commands with:

npx lhci --help

Lighthouse CI supports separate collect, assert, and upload commands, as well as autorun, which performs the configured steps automatically.

6. Create a Lighthouse CI Configuration

Create lighthouserc.cjs in the repository root:

module.exports = {
  ci: {
    collect: {
      staticDistDir: './dist',
      numberOfRuns: 3,
      url: [
        'http://localhost/',
        'http://localhost/blog/',
        'http://localhost/contact/',
      ],
    },
    assert: {
      assertions: {
        'categories:performance': ['warn', { minScore: 0.90 }],
        'largest-contentful-paint': [
          'warn',
          { maxNumericValue: 2500 },
        ],
        'cumulative-layout-shift': [
          'warn',
          { maxNumericValue: 0.10 },
        ],
        'total-blocking-time': [
          'warn',
          { maxNumericValue: 200 },
        ],
      },
    },
    upload: {
      target: 'filesystem',
      outputDir: './lhci-reports',
    },
  },
};

Important details:

  • staticDistDir tells LHCI to serve the local build. You do not have to start a separate web server.
  • When url is used with staticDistDir, LHCI replaces the localhost port with its temporary server port.
  • The listed routes must actually exist in the built site. Replace or remove any that do not.
  • numberOfRuns: 3 reduces the effect of one unusually slow result, but does not eliminate noise.
  • warn prints a finding without failing the job. Use this while establishing a baseline.
  • filesystem keeps results in the CI runner rather than uploading them to public temporary storage.

This example tests three representative URL types. Your production site may need additional routes, including a long tutorial with multiple figures, a category listing, or a page with a working consent banner.

7. Define Performance Budgets That Help Rather Than Distract

A performance budget is a policy for when a metric merits investigation.

For the first version of CI, consider these illustrative starting points:

Audit Example budget Initial action
Lighthouse Performance At least 90/100 Warn
LCP At most 2,500 ms Warn
CLS At most 0.10 Warn
TBT At most 200 ms Warn

Performance budgets for Lighthouse score, LCP, CLS and TBT with distinctions between lab testing and Core Web Vitals field data

Figure 2: Treat budgets as investigation thresholds, not proof of an exact real-world experience.

These limits are not claims about the performance of DuongHoangNam.com. Derive final limits from several stable baseline runs on the routes you maintain.

If you immediately set every budget to 100/100, a small environment fluctuation can create noisy alerts. A maintainable quality gate should focus on meaningful regressions and be strict only where the measurement is sufficiently repeatable.

Lighthouse CI supports warn, error, and off. A failed error assertion returns a non-zero exit code and can stop a CI job; a warn assertion does not.

8. Configure GitHub Actions

Create .github/workflows/lighthouse-ci.yml:

name: Lighthouse CI

on:
  pull_request:
  workflow_dispatch:

permissions:
  contents: read

jobs:
  lighthouse:
    runs-on: ubuntu-latest
    timeout-minutes: 20

    steps:
      - name: Check out repository
        uses: actions/checkout@v4

      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '22'
          cache: npm

      - name: Install dependencies
        run: npm ci

      - name: Build Astro
        run: npm run build

      - name: Run Lighthouse CI
        run: npx lhci autorun

      - name: Upload Lighthouse reports
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: lighthouse-reports
          path: lhci-reports/
          if-no-files-found: warn
          retention-days: 7

This sample runs on pull requests and can also be started manually. It does not need a third-party API key or an external Lighthouse CI server.

Why if: always()? If a later change makes a budget fail, you still want the debugging report to be attached when one was generated. This does not make the failed job pass.

The contents: read permission is sufficient for this simple build-and-audit job. If you later add pull-request comments or other repository mutations, reassess permissions rather than enabling broad write access by default.

The workflow is intentionally separated from deployment. It should not publish to Cloudflare Pages or edit Decap CMS content.

9. Run the First Test and Inspect the Results

Commit the two configuration files on a new branch, open a pull request, and inspect the Lighthouse CI job in GitHub Actions.

A successful execution should:

  1. Install dependencies using the lockfile.
  2. Build the Astro project without errors.
  3. Start Lighthouse against the selected built routes.
  4. Print warnings for any threshold violations.
  5. Save reports under the workflow’s downloadable artifact.

Do not assume a job that completed successfully means every audit met the suggested budgets. With the warn policy, audit warnings are allowed by design.

Download the artifact, open the HTML report for the affected route, and inspect the specific audit rather than relying only on the headline score.

10. Diagnose Common Performance Regressions

A Lighthouse warning becomes useful only when it leads to a focused investigation.

If LCP worsens:

  • Check whether a new hero or featured image is too large.
  • Verify responsive image widths and modern formats such as WebP or AVIF.
  • Check whether the likely LCP image was unnecessarily lazy-loaded.
  • Compare font or stylesheet changes affecting the largest text element.

If CLS worsens:

  • Confirm image and embedded-media dimensions are reserved.
  • Test whether cookie banners, alerts, or dynamic widgets push content unexpectedly.
  • Investigate font swaps and layout changes after hydration.

If TBT worsens:

  • Inspect newly added JavaScript or third-party tags.
  • Check whether scripts load on pages that do not need them.
  • Review client-side hydration and large synchronous tasks.

Troubleshooting Lighthouse CI regressions in Astro with LCP image checks, CLS layout checks and TBT JavaScript checks

Figure 3: Investigate the actual affected resource or interaction before making broad architectural changes.

A single score shift is not proof of a regression. Compare repeated runs, affected URLs, commits, and the environment used for measurement.

A privacy-first site may load Google Analytics only after someone explicitly opts in.

In a fresh Lighthouse browser session, that consent may never be granted. As a result, the local report can omit the analytics scripts that real opted-in visitors receive.

That is expected under a Basic Consent Mode-style implementation, but it changes what the performance test represents.

Use a clear testing policy:

  • Default/no-consent state: confirms performance before optional tracking is loaded.
  • Consented state: separately tests the actual script cost after permission is granted.
  • Rejected state: confirms that declining tracking does not unexpectedly break the interface.

Testing the consented state may require a custom browser automation step or a staging fixture. Do not fake consent by disabling the production privacy logic, and do not treat a default-state audit as a measurement of the entire real-user population.

12. Avoid Testing Only the Homepage

A blog homepage may be fast while a technical article behaves differently.

Long-form tutorials can contain:

  • Multiple high-resolution images.
  • Large code blocks and syntax highlighting.
  • Embedded video or external demonstrations.
  • Sticky navigation and a table of contents.
  • Social widgets and consent-controlled scripts.

A representative test set should include the homepage, a blog listing, one substantial article, and a form page if one exists.

Remember that a URL included in an audit must exist in the same build. A newly created Decap CMS draft might be absent from the published build, and a local static server will not recreate all Cloudflare Pages runtime behavior.

13. When to Turn Warnings into Required Checks

Start with warnings and gather a baseline across several pull requests.

Only after the metrics are reasonably stable should you change selected assertions from warn to error. For example:

'cumulative-layout-shift': [
  'error',
  { maxNumericValue: 0.10 },
],

For a protected branch, you can then configure the GitHub repository’s branch protection or ruleset to require the Lighthouse job to succeed before merging.

Be cautious with stricter LCP or overall score gates, which can fluctuate between machines and environments. You may prefer a warning plus review until the signal is dependable.

A required check should protect the project, not become something contributors routinely bypass.

14. Keep the Reports Private When Appropriate

Lighthouse CI supports temporary public report storage, a self-hosted LHCI server, and filesystem output.

The example in this article uses filesystem output and GitHub Actions artifacts to avoid automatically publishing audit reports to a public temporary URL.

However, GitHub artifacts are still accessible to people with appropriate repository and workflow permissions. They can include requested URLs, page content, and diagnostic information. Do not audit secret-bearing URLs or pages containing private user data without a deliberate access and retention policy.

If you need long-term trend charts, consider a properly secured LHCI server or another monitoring solution. The starter workflow is intended to give practical per-PR feedback, not a full historical analytics service.

15. Add Field Data for a Complete Picture

Lighthouse CI is most valuable when paired with real-user information.

Use PageSpeed Insights or Chrome User Experience Report data when available to evaluate field LCP, CLS, and INP. Look at mobile and desktop separately and remember that field reporting typically aggregates data over a rolling period.

If field data are unavailable for a low-traffic site, do not invent real-user results. Keep using controlled lab measurements while collecting enough trustworthy data.

The useful distinction is:

Lighthouse CI asks: “Did this change potentially make selected pages worse under a repeatable test?”

Field monitoring asks: “What are real visitors actually experiencing?”

You need both perspectives before making broad performance claims.

16. Troubleshooting Setup Problems

Problem Likely cause What to check
npm ci fails Missing/outdated lockfile Commit a matching lockfile; verify Node version
LHCI cannot find site Wrong build output Confirm dist/ or your custom outDir
Audit returns 404 Route absent in static build Use a real generated URL with trailing-slash behavior matched
Chrome startup fails Browser/runtime issue Check runner logs and compatible LHCI release
Reports not uploaded LHCI stopped before output Review collect stage and artifact path
Scores vary between runs Environmental variability Increase repetitions; compare representative results
A production page differs Cloudflare or third-party behavior Test the staging/production environment separately

Do not solve a failing metric by excluding the affected page permanently. First determine whether the failure is a genuine regression, an unsupported runtime requirement, or a test configuration problem.

17. Production Readiness Checklist

Before making Lighthouse CI part of your merge policy, verify:

  • The selected URLs exist in the Astro production build.
  • The build command and lockfile are reproducible.
  • The LHCI version and Node.js version are compatible.
  • At least three runs per page are configured or justified.
  • Initial budgets reflect a measured baseline.
  • Warnings have a documented review process.
  • Reports can be downloaded after a failure.
  • No private URLs or sensitive information appear in reports.
  • Consent and other client-side states are accounted for.
  • Important article pages are tested, not only the homepage.
  • Cloudflare-specific runtime routes are tested separately.
  • Field Core Web Vitals are monitored independently when available.

18. Frequently Asked Questions

Does Lighthouse CI automatically improve my Astro website?

No. It measures selected pages and flags potential problems. Developers must still diagnose and fix them.

Can Lighthouse CI test multiple Astro pages?

Yes. Configure an array of built local URLs under collect.url, or use its static output discovery behavior.

Is a 90/100 Lighthouse score a Google ranking requirement?

No. The score is a lab diagnostic. It is not a guaranteed ranking factor threshold or proof of good field Core Web Vitals.

Does Lighthouse CI measure INP?

Not as a normal page-load audit. INP requires actual interactions; Lighthouse commonly reports TBT as a lab proxy for responsiveness.

Should I fail every PR when Performance drops below 100?

Usually not. Establish repeatable measurements and meaningful budgets before enforcing hard failures.

Can I test Cloudflare Pages Functions using staticDistDir?

Not directly. The local static server serves generated assets. Test dynamic endpoints in a production-like environment.

Can I avoid uploading reports to a public service?

Yes. Use Lighthouse CI’s filesystem upload target and save reports as GitHub Actions artifacts, as in this tutorial.

19. Final Thoughts

Performance is easier to protect when it is part of the development process rather than an occasional cleanup task.

By combining a production Astro build, Lighthouse CI, meaningful assertions, and GitHub Actions artifacts, you can identify suspicious performance changes before they reach visitors. That gives the team a repeatable reason to investigate large images, layout shifts, and unnecessary JavaScript.

Keep the measurement honest. Lab audits are diagnostic signals, not guarantees. Pair them with field data when available, test the states users actually encounter, and introduce strict merge gates only after you understand the expected variability.

The goal is not a perfect score on every run. The goal is to catch avoidable regressions early and preserve a fast, accessible website over time.


Continue Reading

Official Technical References

Technical disclosure: This tutorial provides illustrative source code and a repeatable workflow design; it does not claim that a Lighthouse CI job has been run on this website’s repository or that the example numbers are measured results.

About the Author

Duong Hoang Nam

Duong Hoang Nam

Software engineer sharing practical tutorials, real-world experiments, and insights on AI tools, automation, and web development.

Read My Story →

Related Articles