# .github/workflows/core-web-vitals.yml
# GitHub Actions workflow to enforce Core Web Vitals guardrail.
# Blocks PR merges if metrics degrade (via LHCI assertions against budgets/thresholds).
# Requires: Branch protection rule on 'main' requiring 'Core Web Vitals' status check.
name: Core Web Vitals Guardrail
on:
pull_request:
branches: [main]
jobs:
vitals:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0 # Needed for LHCI budget comparison to base branch
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Build Storybook
run: npm run build-storybook # Assumes this script exists in package.json
- name: Run Lighthouse CI
uses: treosh/lighthouse-ci-action@v11
with:
configPath: .lighthouserc.js # See below
# Optional: GitHub token for uploading builds (enables regression detection)
github-token: ${{ secrets.GITHUB_TOKEN }}
# Temporary public storage for budgets (or use LHCI server/GitHub App for prod)
temporaryPublicStorage: true
Setup Instructions
1. Prerequisites
- Storybook 7+ installed (
@storybook/react or equivalent).
build-storybook script in package.json (e.g., "build-storybook": "storybook build").
- Stories represent realistic component usage (e.g., full pages, high-interaction compositions for FID/INP/CLS).
- GitHub repo with branch protection on
main: Require status check Core Web Vitals / vitals (created automatically by LHCI action).
2. Install Dependencies
npm install --save-dev \
@lhci/cli@^0.16.0 \
http-server \
puppeteer # LHCI uses it internally
3. Create LHCI Config Files
These audit all stories automatically by scraping Storybook's story list and running Lighthouse on each iframe.html?id=... URL.
.lighthouserc.js (core config):
module.exports = {
ci: {
// Collect from Storybook static build
collect: {
staticDistDir: './storybook-static',
numberOfRuns: 5, // Median of 5 runs for stability
puppeteerScript: './.lhci/collect-storybook.js', // Audits ALL stories
},
// Assert: Block on degradation/thresholds
assert: {
// Global performance score (includes Core Web Vitals)
assertions: {
'categories:performance': ['error', { minScore: 0.85 }], // Fail PR if <85
// Core Web Vitals thresholds (adjust per your perf budget)
'largest-contentful-paint': ['warn', { maxNumericValue: 2500, averageNumericValue: 2000 }],
'cumulative-layout-shift': ['error', { maxNumericValue: 0.1 }],
'interaction-to-next-paint': ['warn', { maxNumericValue: 200 }], // INP (replaces FID)
'first-contentful-paint': ['warn', { maxNumericValue: 1800 }],
'total-blocking-time': ['warn', { maxNumericValue: 300 }],
// No regressions >10% from base branch (auto-detected via LHCI builds)
'budgets': [
{
path: '**/*', // All Storybook story paths
budgets: {
'largest-contentful-paint': { maxNumericValue: 110 }, // 10% budget
'cumulative-layout-shift': { maxNumericValue: 110 },
'interaction-to-next-paint': { maxNumericValue: 110 },
},
},
],
},
},
// Upload artifacts for regression tracking (compares to base/main)
upload: {
target: 'github', // Uses GITHUB_TOKEN; enables base branch comparison
},
// Optional: Server for prod (lhci.app or self-hosted)
// serverUrl: 'https://your-lhci-server.com',
// serverBaseUrl: 'https://your-lhci-server.com/app',
},
};
.lhci/collect-storybook.js (Puppeteer script to audit all stories):
// From official LHCI Storybook recipe: https://github.com/GoogleChrome/lighthouse-ci/blob/main/docs/recipes-storybook.md
const puppeteer = require('puppeteer');
async function getStories(page) {
await page.goto(`${page.urlPrefix}/iframe.html`, { waitUntil: 'networkidle0' });
return await page.evaluate(() => {
// Extract all story IDs from Storybook manager (works for SB 7+)
return Array.from(document.querySelectorAll('a[href^="/story/"], a[data-sb-kind], [data-testid*="story"]'))
.map(a => {
const href = a.getAttribute('href');
const idMatch = href.match(/id=([^&]+)/);
return idMatch ? { id: idMatch[1] } : null;
})
.filter(Boolean);
});
}
module.exports = async (context) => {
const { page } = context;
const stories = await getStories(page);
console.log(`Auditing ${stories.length} stories...`);
for (const story of stories) {
const url = `${context.urlPrefix}/iframe.html?id=${story.id}&viewMode=story`;
await page.goto(url, { waitUntil: 'networkidle0' });
// Simulate interaction for INP/FID (adjust for your components)
await page.waitForTimeout(1000);
await page.mouse.click(100, 100); // Generic tap
await page.waitForTimeout(500);
await context.send('auditorun:report', { url: page.url() });
}
};
.lhci/get-stories.js (helper, optional for static list):
// Fallback: Manually list critical stories/paths for guardrail
// e.g., module.exports = async () => [{ id: 'button--primary' }, { id: 'page--home' }];
module.exports = async (page) => []; // Use dynamic scraper above
4. Optional: Manual Budgets for Baselines
Create budgets.json (LHCI loads it automatically):
{
"largest-contentful-paint": { "maxNumericValue": 2000 },
"cumulative-layout-shift": { "maxNumericValue": 0.05 }
}
- Run locally:
npx lhci autorun to test.
- On
main merges, LHCI auto-generates baselines via GitHub uploads.
5. Test Locally
npm run build-storybook
npx lhci autorun # Serves static, audits all stories, applies assertions
6. Customization & Best Practices
- Key Stories Only: Modify
collect-storybook.js to filter stories (e.g., story.id.includes('--usage') for *-usage.stories.tsx).
- Simulate Real Usage: Add interactions (clicks, scrolls) in puppeteerScript. Use
@storybook/test for automated stories.
- Degradation Detection: LHCI compares medians to base branch builds (via GitHub uploads). Tune budgets for 5-10% tolerance.
- Thresholds: Start permissive (
warn), tighten to error. Monitor via LHCI dashboard.
- Edge Cases: Mobile emulation auto-enabled; add
formFactor: 'desktop' if needed.
- Performance Addons: Pair with
@storybook/addon-performance for dev-time insights.
- Prod Scale: Use LHCI GitHub App (free tier) for persistent builds/serverless hosting.
This guardrail blocks merges automatically if any story's Core Web Vitals degrade. PRs show detailed Lighthouse reports in checks. Metrics improve iteratively as components optimize!
If your Storybook version differs or needs framework tweaks (e.g., Vue/NX), provide details for refinements. 🔍