Lighthouse Accessibility Audits in CI/CD: Automate WCAG Checks

Lighthouse Accessibility Audits in CI/CD: Automate WCAG Checks

Lighthouse is Google's open-source auditing tool for web pages. Most developers know it from Chrome DevTools, but Lighthouse CI (lhci) makes it a first-class part of any CI/CD pipeline — running audits on every pull request, tracking scores over time, and blocking merges when accessibility scores drop below your threshold.

This guide covers lighthouse-ci setup from scratch, configuring the accessibility audit category, setting thresholds, interpreting scores, and understanding what Lighthouse catches versus axe-core.

What Lighthouse Measures

Lighthouse produces scores across five categories: Performance, Accessibility, Best Practices, SEO, and PWA. Each score is 0–100.

The Accessibility score is a weighted average of individual audit results. Audits map to WCAG success criteria and are powered by axe-core under the hood — so Lighthouse's accessibility findings are a subset of what @axe-core/playwright would find, but presented with weights and an aggregate score.

Key characteristic: Lighthouse accessibility scoring is designed to be a progress indicator, not a compliance certification. A score of 100 does not mean WCAG compliance. It means all automatically detectable issues that Lighthouse checks for were not found.

Installing Lighthouse CI

npm install --save-dev @lhci/cli

Or globally for local use:

npm install -g @lhci/cli

Verify the installation:

npx lhci --version
# @lhci/cli/0.14.0 linux-x64 node-v20.11.0

Basic Configuration

Create lighthouserc.js (or .lighthouserc.json) in your project root:

// lighthouserc.js
module.exports = {
  ci: {
    collect: {
      url: [
        'http://localhost:3000/',
        'http://localhost:3000/about',
        'http://localhost:3000/contact',
      ],
      numberOfRuns: 3,
      startServerCommand: 'npm run start',
      startServerReadyPattern: 'listening on port',
      settings: {
        // Only run accessibility — faster than full audit
        onlyCategories: ['accessibility'],
        // Or run all categories
        // onlyCategories: ['performance', 'accessibility', 'best-practices', 'seo'],
      },
    },
    assert: {
      preset: 'lighthouse:no-pwa',
      assertions: {
        'categories:accessibility': ['error', { minScore: 0.9 }],
      },
    },
    upload: {
      target: 'temporary-public-storage',
    },
  },
};

Run it locally:

npx lhci autorun

This command runs the collect, assert, and optionally upload phases in sequence.

Configuring Accessibility Score Thresholds

The assertion format is [severity, { minScore }] where severity is either 'warn' or 'error':

assert: {
  assertions: {
    // Fail the CI run if accessibility score drops below 0.9 (90)
    'categories:accessibility': ['error', { minScore: 0.9 }],

    // Warn (non-blocking) if performance drops below 0.8
    'categories:performance': ['warn', { minScore: 0.8 }],
  },
},

For stricter enforcement, assert individual audit results rather than the aggregate score:

assert: {
  assertions: {
    // Core accessibility audits — error on any failure
    'color-contrast': 'error',
    'image-alt': 'error',
    'label': 'error',
    'link-name': 'error',
    'button-name': 'error',
    'document-title': 'error',
    'html-has-lang': 'error',
    'meta-viewport': 'error',

    // Warn on these
    'heading-order': 'warn',
    'landmark-one-main': 'warn',
    'region': 'warn',
  },
},

Individual audit assertion values:

  • 'off' — ignore this audit
  • 'warn' — report but don't fail
  • 'error' — fail the run if audit fails

With a numeric option object: ['error', { minScore: 1 }] means "error if this audit's score is below 1.0 (i.e., if it doesn't pass)".

Budget Configuration

Lighthouse CI supports budget files that define score floors per page. This is more granular than global thresholds:

// budget.json
[
  {
    "path": "/",
    "timings": [
      { "metric": "interactive", "budget": 5000 }
    ],
    "resourceSizes": [
      { "resourceType": "total", "budget": 500 }
    ]
  }
]

Reference in your config:

collect: {
  settings: {
    budgetPath: './budget.json',
  },
},

For accessibility-specific budgets, the individual audit assertions in lighthouserc.js are more flexible than budget files.

GitHub Actions Integration

# .github/workflows/lighthouse.yml
name: Lighthouse CI

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  lighthouse:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'

      - name: Install dependencies
        run: npm ci

      - name: Build application
        run: npm run build

      - name: Run Lighthouse CI
        run: npx lhci autorun
        env:
          LHCI_GITHUB_APP_TOKEN: ${{ secrets.LHCI_GITHUB_APP_TOKEN }}

      - name: Upload Lighthouse results
        uses: actions/upload-artifact@v4
        if: always()
        with:
          name: lighthouse-results
          path: .lighthouseci/

The LHCI_GITHUB_APP_TOKEN enables the GitHub status check integration — Lighthouse CI will post a check to your PR with scores and links to the report. Install the Lighthouse CI GitHub App to get this working.

For PRs, add a PR comment with the scores using treosh/lighthouse-ci-action:

- name: Run Lighthouse CI
  uses: treosh/lighthouse-ci-action@v11
  with:
    urls: |
      http://localhost:3000/
      http://localhost:3000/about
    budgetPath: ./budget.json
    uploadArtifacts: true
    temporaryPublicStorage: true
  env:
    LHCI_GITHUB_APP_TOKEN: ${{ secrets.LHCI_GITHUB_APP_TOKEN }}

Interpreting Lighthouse Accessibility Scores

Score Weights

The accessibility score is a weighted average. High-impact audits carry more weight:

Audit Weight WCAG Criterion
color-contrast 7 1.4.3
image-alt 10 1.1.1
label 10 1.3.1
link-name 3 2.4.4
document-title 3 2.4.2
html-has-lang 7 3.1.1
td-headers-attr 3 1.3.1

This means fixing image-alt or label violations has a larger impact on the score than fixing link-name. Use this to prioritize.

Reading the Report

After lhci autorun, reports are stored in .lighthouseci/. Each run produces a .html report and a .json data file.

The JSON structure for accessibility:

{
  "categories": {
    "accessibility": {
      "id": "accessibility",
      "title": "Accessibility",
      "score": 0.91,
      "auditRefs": [...]
    }
  },
  "audits": {
    "color-contrast": {
      "id": "color-contrast",
      "title": "Background and foreground colors have a sufficient contrast ratio",
      "description": "Low-contrast text is difficult or impossible for many users to read...",
      "score": 0,
      "scoreDisplayMode": "binary",
      "details": {
        "type": "table",
        "items": [
          {
            "node": {
              "snippet": "<span class=\"text-muted\">Last updated 3 days ago</span>",
              "nodeLabel": "Last updated 3 days ago"
            }
          }
        ]
      }
    }
  }
}

Parse results programmatically:

const fs = require('fs');
const path = require('path');

const resultsDir = '.lighthouseci';
const files = fs.readdirSync(resultsDir).filter(f => f.endsWith('.json'));

files.forEach(file => {
  const data = JSON.parse(fs.readFileSync(path.join(resultsDir, file), 'utf8'));
  const a11yScore = data.categories.accessibility.score;
  const failedAudits = Object.values(data.audits)
    .filter(a => a.score === 0 && a.scoreDisplayMode === 'binary');

  console.log(`Score: ${Math.round(a11yScore * 100)}`);
  console.log('Failed audits:');
  failedAudits.forEach(a => console.log(`  - ${a.id}: ${a.title}`));
});

Collecting Multiple Runs for Stability

Lighthouse scores can vary between runs due to network conditions and timing. For accessibility audits this is less of a concern than for performance (accessibility is mostly static), but using numberOfRuns: 3 and the median result is still good practice:

collect: {
  numberOfRuns: 3,
  // lhci uses the median run automatically for assertions
},

For accessibility-only audits, numberOfRuns: 1 is usually sufficient since results are deterministic.

Lighthouse Server for Historical Tracking

For long-lived projects, set up Lighthouse CI Server to track scores over time and catch gradual regressions:

# Run the LHCI server
docker run -p 9001:9001 patrickhulce/lhci-server

# Or with Docker Compose
version: '3'
services:
  lhci-server:
    image: patrickhulce/lhci-server
    ports:
      - '9001:9001'
    volumes:
      - lhci-data:/data
volumes:
  lhci-data:

Update your config to upload to the server:

upload: {
  target: 'lhci',
  serverBaseUrl: 'https://your-lhci-server.example.com',
  token: process.env.LHCI_BUILD_TOKEN,
},

Generate a build token on your LHCI server:

npx lhci wizard
# Follow prompts to create a project and get a build token

The LHCI server dashboard shows score trends over time, making it easy to see when and why accessibility scores changed.

What Lighthouse Catches vs. axe-core

Lighthouse accessibility audits are powered by axe-core, but they're not the same:

Lighthouse runs a subset of axe-core rules — specifically the rules that map to audits with defined weights in the Lighthouse scoring algorithm. Not all axe-core rules appear as Lighthouse audits.

axe-core (via @axe-core/playwright) gives you:

  • The full axe-core rule set (~80 rules)
  • Component-level scanning
  • Dynamic state testing (open modals, error states)
  • Zero false positives (conservative rule set)
  • Granular violation data including element selectors

Lighthouse gives you:

  • An aggregate score (0–100) useful for tracking trends
  • Integration with performance, SEO, and best practice audits in one run
  • Historical tracking via LHCI Server
  • PR status checks with score comparisons
  • Broader browser simulation (mobile throttling, etc.)
Capability Lighthouse axe-core/Playwright
Aggregate score Yes No
Historical tracking Yes (LHCI Server) No (need external tooling)
Full axe-core rule set Partial Full
Component scanning No Yes
Dynamic state testing No Yes
CI integration Native Via test framework
Score threshold gates Yes Violation count gates

For most projects, use both:

  • Lighthouse CI for PR score gates and trend tracking
  • axe-core in Playwright for granular component and interactive state coverage

Practical Threshold Strategy

Starting from zero, the path to a meaningful accessibility gate:

Week 1: Baseline

npx lhci collect --url=https://yoursite.com
# Check the score — say it's 72

Week 1: Set a lenient gate

'categories:accessibility': ['error', { minScore: 0.7 }],

This prevents regression below your current state without blocking the team.

Ongoing: Ratchet upward

As you fix violations:

// Month 1
'categories:accessibility': ['error', { minScore: 0.8 }],

// Month 2
'categories:accessibility': ['error', { minScore: 0.9 }],

// Month 3 (target)
'categories:accessibility': ['error', { minScore: 0.95 }],

Never lower the threshold. Only raise it as issues are fixed.

Auditing a Pre-Built Static Site

For static sites (Next.js with next export, Gatsby, Astro), serve the build locally before running lhci:

// lighthouserc.js
module.exports = {
  ci: {
    collect: {
      staticDistDir: './out', // or './public', './dist'
      url: [
        'http://localhost/index.html',
        'http://localhost/about/index.html',
      ],
    },
    // ...
  },
};

Lighthouse CI will spin up a local server pointing at staticDistDir automatically.

Common Accessibility Audits and Fixes

html-has-lang — Missing language attribute

<!-- Violation -->
<html>

<!-- Fix -->
<html lang="en">

document-title — Missing or empty page title

<!-- Violation -->
<title></title>

<!-- Fix -->
<title>Dashboard | MyApp</title>

meta-viewport — Viewport disables text scaling

<!-- Violation -->
<meta name="viewport" content="width=device-width, user-scalable=no">

<!-- Fix -->
<meta name="viewport" content="width=device-width, initial-scale=1">

aria-required-children — ARIA parent/child role mismatch

<!-- Violation -->
<ul role="listbox">
  <li>Option 1</li> <!-- Should have role="option" -->
</ul>

<!-- Fix -->
<ul role="listbox">
  <li role="option">Option 1</li>
</ul>

link-name — Links without accessible names

<!-- Violation -->
<a href="/dashboard"><img src="icon.svg"></a>

<!-- Fix -->
<a href="/dashboard" aria-label="Dashboard">
  <img src="icon.svg" alt="">
</a>

Integrating with Existing Quality Gates

Lighthouse CI works alongside other quality tools in CI:

jobs:
  quality:
    runs-on: ubuntu-latest
    steps:
      - name: Unit tests
        run: npm test

      - name: Build
        run: npm run build

      - name: Start server
        run: npm run serve &

      - name: E2E tests
        run: npx playwright test

      - name: Accessibility audit (Lighthouse)
        run: npx lhci autorun

      - name: Accessibility tests (axe-core via Playwright)
        run: npx playwright test --grep @accessibility

Running both Lighthouse and axe-core Playwright tests catches more: Lighthouse for aggregate score tracking and trend detection, axe-core for component-level regression prevention.

Lighthouse CI makes accessibility a tracked metric rather than an afterthought. Once your score is visible in every PR, teams naturally stop introducing new violations and gradually improve existing ones. That cultural shift — from "we'll fix accessibility later" to "this PR dropped the score by 3 points" — is the real value of lighthouse-ci in a CI pipeline.

Read more

Start now free