The user wants to engineer a "Core Web Vitals guardrail" within Storybook. This guardrail should block merges (presumably in a CI/CD pipeline) if component usage degrades specific performance metrics.
Deconstruct the Request:
- Goal: Create a guardrail to protect Core Web Vitals (CWV).
- Environment: Storybook.
- Trigger: Component usage (presumably testing the component in isolation or in a specific story).
- Action: Block merges (fail a CI status check).
- Condition: Metrics degrade (regression compared to a baseline).
Key Components Needed:
- Performance Testing Tool: We need something to measure CWV (LCP, FID/INP, CLS). Lighthouse is the standard here, specifically via Chrome DevTools protocol. Playwright or Puppeteer are often used to drive this, but Lighthouse has a CLI.
- Storybook Integration: How do we run these tests on stories?
- Storybook Test Runner is the modern way to interact with stories programmatically.
- We need to target specific stories that represent "component usage."
- Baseline Management: How do we know if metrics degraded? We need a way to store "golden" metrics (e.g., a JSON file committed to the repo) and compare new results against them.
- CI Integration: The actual "block merge" happens in the CI system (GitHub Actions, GitLab CI, etc.). The script needs to return a non-zero exit code.
Step-by-Step Implementation Plan:
-
The "Runner" (Script): I need a Node.js script that:
- Starts a build of the Storybook (or connects to a deployed one).
- Uses a tool to audit specific stories.
- Collects CWV data.
- Compares against a baseline.
- Fails if regression exceeds a threshold.
-
The Tooling Choice:
- Option A:
@storybook/test-runner + axe-playwright etc. (Good for a11y, harder for pure CWV network/render timing without Lighthouse).
- Option B:
lighthouse CLI programmatically. This is robust.
- Option C:
unlighthouse. Good for scanning whole sites.
- Option D:
web-vitals library injection. Very accurate for real user metrics (RUM), but harder to script in CI for synthetic testing without a browser harness.
Decision: Using the Lighthouse Node module combined with Puppeteer (or just Lighthouse on a specific URL) is the most standard way to get synthetic CWV data in CI. Since Storybook serves static pages (Iframes or Canvas), we can audit the iframe.html URL or the specific story URL directly.
-
The "Guardrail" Logic:
- Load
baseline.json.
- Run Lighthouse on specific stories.
- Calculate differences.
- Save new results (optional, for artifacts).
- Throw error if
new_score < baseline_score - threshold.
-
Storybook Specifics:
- Storybook stores stories as
storyId.
- URL format is usually
iframe.html?id=components-button--primary&viewMode=story.
Drafting the Solution Structure:
- Prerequisite: A CI workflow.
- Step 1: Install dependencies (
lighthouse, chrome-launcher).
- Step 2: Create the Audit Script (
audit-cwv.js).
- Step 3: Define the Baseline (
performance-baseline.json).
- Step 4: Integrate into CI (GitHub Actions example).
Refining the Audit Script:
It needs to look something like this:
const lighthouse = require('lighthouse');
const chromeLauncher = require('chrome-launcher');
const fs = require('fs');
// Config
const STORYBOOK_URL = process.env.STORYBOOK_URL || 'http://localhost:6006';
const STORIES_TO_TEST = [
'example-introduction--page',
'example-button--primary',
];
const THRESHOLDS = {
'largest-contentful-paint': 2500, // ms
'cumulative-layout-shift': 0.1, // score
// Note: FID is hard to simulate in Lighthouse, usually rely on Total Blocking Time (TBT) or Interaction to Next Paint (INP) depending on Lighthouse version. TBT is a good proxy for lab data.
'total-blocking-time': 300 // ms
};
Wait, blocking merges based on strict synthetic thresholds is often flaky. A better approach for the user request ("degrades metrics") implies regression testing against a baseline.
Revised Logic:
- Read
vitals-baseline.json.
- Run Lighthouse.
- Compare
result vs baseline.
- If
result > baseline * 1.1 (10% regression), FAIL.
Implementation Details:
- Challenge: Lighthouse cleans the cache. Storybook lazy loads. This is good.
- Challenge: Flakiness. Need to run multiple times or accept that CI variance exists. For a "guardrail," we should be slightly lenient or use averages. I'll stick to a single run for simplicity in the example, but add a note about variance.
Code Structure to Generate:
scripts/measure-vitals.js: The engine.
vitals-baseline.json: The storage.
.github/workflows/cwv-guard.yml: The CI config.
Self-Correction during thought process:
Running Lighthouse on every component might be slow. The prompt implies "component usage." I should suggest tagging specific stories as "critical" or "performance-sensitive" so the CI doesn't take an hour.
Actually, Storybook 7/8 has a test-runner. Can we use that?
The @storybook/test-runner runs Playwright. Playwright can get LCP/CLS using the web-vitals library.
Comparing approaches:
- Lighthouse: Heavyweight, gives a full report, standard "crux" simulation. Good for holistic view.
- Playwright + web-vitals: Lightweight, measures actual browser observability.
- Decision: Lighthouse is more "standard" for "Core Web Vitals" discussions in engineering circles regarding CI, as it provides the "Audits." I will stick to Lighthouse CLI via Node.js for clarity and robustness.
Final Plan:
- Concept: Explain the architecture (Lighthouse + Node Script + CI).
- The Script: A robust Node.js script that launches Chrome, runs Lighthouse against specific Storybook URLs, and compares results against a local JSON file.
- The Baseline: How to generate and update it.
- The CI: How to put it in GitHub Actions to block the PR.
Let's write the code.
Script logic:
- Import
lighthouse, chrome-launcher.
- List of Story IDs.
- Loop through IDs ->
lighthouse(url, opts).
- Extract LCP, CLS, TBT (lab data proxy for INP/FID).
- Check against
baseline.json.
console.error if failed.
process.exit(1) if failed.
Optimization: I should handle the "First Load" scenario where baseline doesn't exist (just generate it and pass).
Let's refine the "Degrades Metrics" part. If there is no baseline, create one. If there is, compare.
Threshold for regression: e.g., > 10% or absolute value (e.g., > 100ms).
Let's construct the response.
Outline:
- Introduction: High-level strategy.
- Dependencies:
lighthouse, chrome-launcher.
- The Audit Script: The core logic.
- The Baseline Mechanism: JSON file handling.
- CI Integration: GitHub Actions YAML.
- Refinement: Handling Flakiness & Cold Starts.
One crucial detail: Storybook usually runs in development mode locally, but in CI for performance testing, you should build the static Storybook (npm run build-storybook) and serve it (npx http-server storybook-static) to get accurate production-like metrics (minified code, etc.). I must emphasize this.
Let's write the code blocks mentally.
const runnerResult = await lighthouse(url, opts, config);
const metrics = { lcp: runnerResult.lhr.audits['largest-contentful-paint'].numericValue, ... }
Okay, ready to generate.
Designing a Core Web Vitals (CWV) guardrail in Storybook requires shifting from "visual verification" to "performance verification."
We will achieve this by building a custom Node.js script that runs after the Storybook build in your CI pipeline. This script will use Lighthouse to programmatically audit specific "critical stories," compare the results against a stored baseline, and exit with an error code (blocking the merge) if thresholds are breached.
Here is the engineering implementation.
1. Architecture & Dependencies
We need a programmatic way to run Lighthouse on the statically built Storybook assets.
Install Dependencies:
npm install --save-dev lighthouse chrome-launcher fs-extra
2. The Configuration Strategy
You shouldn't run this on every story (too slow). Define a configuration that targets "Critical Usage Stories"—stories that represent high-impact components (e.g., Homepage, ProductCard, Navigation).
Create a file named cwv.guardian.config.js:
// cwv.guardian.config.js
module.exports = {
// The specific stories to audit.
// These should be the IDs found in the URL when viewing Storybook.
stories: [
'components-button--primary-usage',
'layouts-grid--dashboard-view'
],
// Thresholds (in milliseconds or score 0-1)
// If metrics exceed these values compared to baseline, block the merge.
thresholds: {
LCP: 2500, // Largest Contentful Paint (ms)
FID: 100, // First Input Delay (ms) - Simulated
CLS: 0.1, // Cumulative Layout Shift (score)
TBT: 200 // Total Blocking Time (ms) - Proxy for INP
},
// Allowed regression percentage (e.g., 5% slower is okay, 10% is not)
regressionTolerance: 0.05
};
3. The Guardian Script
Create a script cwv.guardian.js. This script will launch Chrome, run Lighthouse on the configured stories, and compare the results against a vitals-baseline.json.
// scripts/cwv.guardian.js
const lighthouse = require('lighthouse');
const chromeLauncher = require('chrome-launcher');
const fs = require('fs');
const path = require('path');
const config = require('../cwv.guardian.config');
const STORYBOOK_URL = process.env.STORYBOOK_URL || 'http://localhost:6006';
const BASELINE_FILE = path.join(__dirname, '../vitals-baseline.json');
async function runLighthouse(url) {
const chrome = await chromeLauncher.launch({ chromeFlags: ['--headless', '--no-sandbox'] });
const options = {
logLevel: 'error',
output: 'json',
onlyCategories: ['performance'],
port: chrome.port,
};
const runnerResult = await lighthouse(url, options);
// Extract specific metrics
const audits = runnerResult.lhr.audits;
await chrome.kill();
return {
LCP: audits['largest-contentful-paint'].numericValue,
FID: audits['max-potential-fid'].numericValue, // Lab proxy for FID
CLS: audits['cumulative-layout-shift'].numericValue,
TBT: audits['total-blocking-time'].numericValue,
};
}
async function validate() {
console.log(`\n🛡️ Starting Core Web Vitals Guardian...`);
console.log(`🎯 Target: ${STORYBOOK_URL}`);
// 1. Load Baseline
let baseline = {};
if (fs.existsSync(BASELINE_FILE)) {
baseline = JSON.parse(fs.readFileSync(BASELINE_FILE));
} else {
console.warn('⚠️ No baseline found. This run will generate one.');
}
let hasFailure = false;
for (const storyId of config.stories) {
const url = `${STORYBOOK_URL}/iframe.html?id=${storyId}&viewMode=story`;
console.log(`\n🔍 Auditing story: ${storyId}`);
try {
const metrics = await runLighthouse(url);
console.table(metrics);
const storyBaseline = baseline[storyId];
if (!storyBaseline) {
console.log('ℹ️ New story detected. Saving current metrics as baseline.');
baseline[storyId] = metrics;
continue;
}
// 2. Comparison Logic
for (const [key, value] of Object.entries(metrics)) {
const baseValue = storyBaseline[key];
const threshold = config.thresholds[key];
// Check Absolute Thresholds
if (value > threshold) {
console.error(`❌ FAILED: ${key} (${value.toFixed(2)}) exceeds absolute threshold (${threshold}).`);
hasFailure = true;
continue;
}
// Check Regression
const change = (value - baseValue) / baseValue;
if (change > config.regressionTolerance) {
console.error(`❌ REGRESSION: ${key} slowed down by ${(change * 100).toFixed(1)}%.`);
hasFailure = true;
} else {
console.log(`✅ PASSED: ${key} within tolerance.`);
}
}
// Update baseline if performance improved (optional optimization)
baseline[storyId] = metrics;
} catch (error) {
console.error(`🚨 Error auditing ${storyId}:`, error.message);
hasFailure = true;
}
}
// 3. Save updated baseline (if valid)
if (!hasFailure) {
fs.writeFileSync(BASELINE_FILE, JSON.stringify(baseline, null, 2));
console.log('\n✅ Baseline updated successfully.');
}
if (hasFailure) {
console.error('\n🚫 Merge Blocked: Performance degradation detected.');
process.exit(1); // Exit code 1 blocks the CI pipeline
} else {
console.log('\n🟢 All checks passed. Safe to merge.');
process.exit(0);
}
}
validate();
4. CI Integration (GitHub Actions)
To make this a true "Guardrail," it must run in CI against a production-like build.
Prerequisites:
- Build the Storybook static site (
npm run build-storybook).
- Serve the static site (using
npx http-server or similar).
Workflow Example (.github/workflows/ci.yml):
name: Storybook CI
on: [pull_request]
jobs:
vitals-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node
uses: actions/setup-node@v3
with:
node-version: 18
cache: 'npm'
- name: Install Dependencies
run: npm ci
- name: Build Storybook
run: npm run build-storybook
- name: Run Vitals Guardian
run: |
# Start server in background
npx http-server storybook-static --port 6006 &
# Wait for server to be ready
npx wait-on http://localhost:6006
# Run the guardrail script
node scripts/cwv.guardian.js
env:
STORYBOOK_URL: http://localhost:6006
5. Handling Baseline Updates
The first time this runs, it will create vitals-baseline.json. You should commit this file to your repository.
- Scenario A (Improvement): A developer optimizes the code. The script sees lower numbers, updates the JSON file, and passes. The PR includes the updated JSON.
- Scenario B (Regression): A developer adds a heavy library. The script sees higher numbers, fails, and blocks the merge. They must either optimize the code or, if the regression is intentional/acceptable, manually update the baseline numbers in the JSON file (requiring code review).
Key Considerations for Stability
- Cold Start Variance: CI environments are noisy. Lighthouse results can fluctuate.
- Fix: In a production setup, run Lighthouse 3 times per story and take the median in the
runLighthouse function.
- Storybook Overhead: Storybook itself adds overhead (iframe, manager UI).
- Fix: Always audit the
iframe.html endpoint (as shown in the script), which isolates the component rendering context, removing most Storybook manager UI noise.
- Mock Data: Ensure your stories use realistic data structures. Auditing a component with a "loading" skeleton doesn't help if the real data causes LCP delays.