We are going to create a Storybook addon that acts as a guardrail for Core Web Vitals (CWV). The idea is to block merges (or at least warn) when a component's usage in Storybook degrades the metrics.
Steps:
- We need to measure the Core Web Vitals for each story (component example) in Storybook. The main metrics are LCP, FID, CLS, and maybe others.
- We need to set thresholds for these metrics.
- When a story is rendered in Storybook, we will measure the metrics and compare them to the thresholds.
- If the metrics degrade (i.e., are worse than the thresholds), we will display a warning or error in the Storybook UI and potentially block the merge (if integrated into CI/CD).
However, note that Storybook runs in the browser, so we can only measure the metrics in the context of the Storybook instance. We are not measuring the component in the actual production app, but we can get an indication.
Approach:
- Use the
web-vitals library to measure the metrics in the browser.
- We'll create a Storybook addon that registers a listener for the story render and then measures the metrics for that story.
Implementation plan:
- Create a new Storybook addon.
- The addon will have a panel that shows the measured metrics for the current story and whether they pass the thresholds.
- We'll also provide a way to configure the thresholds (maybe via a config file or environment variables).
But note: The requirement is to block merges. So we need to integrate with the CI/CD. We can do:
- In the CI, we run Storybook in a headless browser (like Puppeteer) and run the addon to collect the metrics for each story.
- Then, we compare the metrics to the thresholds. If any story fails, we exit with an error.
However, the addon itself is for the Storybook UI. For CI, we might need a separate script that uses the same measurement logic but in a headless environment.
Alternatively, we can design the addon to work both in the browser and in a headless environment (with Storybook's --headless mode).
Let's break it down:
Part 1: The addon for measuring and displaying metrics in Storybook UI.
Part 2: A CLI or script that runs Storybook in headless mode, collects the metrics, and fails if thresholds are not met.
But note: The addon is a UI addon, so in headless mode we don't need the UI. We can extract the measurement logic into a separate package that both the addon and the CI script use.
Steps for the addon:
- Install
web-vitals and any other required dependencies.
- Create an addon that registers a
web-vitals observer for each story render.
- The observer will collect the metrics and then we can store them in the story's context or in a global store.
- We display the metrics in a panel.
However, note that web-vitals metrics are measured for the entire page, not per component. So when we render a story, we are measuring the entire Storybook page. This might not be accurate because the Storybook UI itself (sidebar, toolbar, etc.) affects the metrics.
We need to isolate the component. We can try to measure the metrics for the component's iframe (if Storybook uses iframes for each story) but by default, Storybook does not use iframes for each story. We might need to enable iframes for each story? That would be heavy.
Alternatively, we can measure the metrics for the entire page and then try to subtract the baseline (the Storybook UI without the story). But that's complex.
Another idea: Use the web-vitals library in the context of the story's iframe (if we can get the iframe). But note that the addon runs in the main Storybook window, not in the story's iframe.
We might need to inject code into the story's iframe to measure the metrics there. But then how do we get the data back?
Let's consider:
Option 1: Measure in the main window and hope that the component doesn't get affected by the Storybook UI. This is not ideal.
Option 2: Use Storybook's iframe mode (if available) and then communicate from the iframe to the main window.
Storybook has a preview.js that runs in the iframe (if iframes are enabled). We can use that to measure the metrics in the iframe and then send them to the main window via window.parent.postMessage.
Steps for iframe mode:
-
Enable iframe for stories in Storybook configuration (if not already). This is done by setting framework: { iframe: true } in .storybook/main.js? Actually, in Storybook 7, the iframe is enabled by default for the preview, but we can also set iframe: 'strict' for each story? We might need to check.
-
In the addon, we can register a preview (runs in the iframe) and a manager (runs in the main window) entry.
-
In the preview entry, we will measure the web-vitals and then post the metrics to the main window.
-
In the manager entry, we listen for the message and then store the metrics for the current story.
But note: The web-vitals metrics are for the entire iframe (which is the story plus the Storybook preview iframe chrome). Actually, the iframe for a story in Storybook is the entire preview area? I think so.
Alternatively, we can try to measure only the story's root element? The web-vitals library doesn't support that.
Given the complexity and the fact that we are measuring in a controlled environment (Storybook), we might have to accept that we are measuring the entire preview iframe. We can set a baseline by measuring the Storybook preview without any story? But then we are comparing two different pages.
This is getting complicated.
Let's look for existing solutions:
There is a Storybook addon called @storybook/addon-performance that measures performance. It uses performance API and web-vitals? Let's check:
@storybook/addon-performance uses PerformanceObserver and measures FCP, LCP, etc. for the entire page.
So it seems they measure the entire page.
We might have to do the same.
But note: The requirement is to measure the component's usage. However, if we are measuring the entire page, then the Storybook UI (which is constant) will be included. So the differences between stories might be due to the component.
However, if one story uses a heavy component and another uses a light one, the metrics will reflect that.
So maybe it's acceptable.
Implementation:
-
Create an addon that uses web-vitals to measure the metrics for the current story (in the main window, or in the iframe and then send to main window).
-
We'll measure when the story is rendered and then when the metrics are available, we store them.
-
We display the metrics in a panel.
-
We set thresholds (configurable) and if any metric is above (worse than) the threshold, we mark it as failed.
-
In the UI, we show a warning or error.
-
For CI, we run Storybook in headless mode, and we have a script that collects the metrics from the addon (maybe by reading the store or by having the addon write to a file or by using the Storybook API to get the metrics). Alternatively, we can run the same measurement code in the CI script without the UI.
However, the addon is designed for the UI. We might want to split the measurement logic into a separate package that can be used both in the addon and in the CI.
Let's design:
Package 1: core-web-vitals-guardrail-measure - a function that, given a DOM element (or the whole document) and options (thresholds), measures the metrics and returns the results.
But note: web-vitals doesn't take a DOM element. It measures for the entire page.
So we cannot measure a specific component without an iframe.
Given the constraints, we might have to measure the entire page.
Steps for the addon:
-
In the addon's manager entry, we set up a listener for story changes (using events from Storybook).
-
When a story is rendered, we wait for the metrics to be collected (using web-vitals).
-
We store the metrics for that story in a global object (key by storyId).
-
We display the metrics in a panel for the current story.
-
We also show an overall status (if the current story passes or fails).
For headless mode (CI):
We can run Storybook with --headless and then use a script that:
- Starts Storybook in headless mode (with the addon enabled).
- For each story, we wait for the metrics to be collected and then we read them from the store (via the Storybook channel? or by having the addon write to a file?).
Alternatively, we can run the same measurement code in the CI without Storybook? But then we are not measuring the component in the Storybook context.
We want to measure the component as it is in Storybook.
So we need to run Storybook and then collect the metrics from the addon.
How can we get the metrics from the addon in headless mode?
We can have the addon, when in headless mode, write the metrics to a JSON file (on the server side? but we are in the browser). Or we can have the addon send the metrics via the Storybook channel to the manager (which is also running in the headless browser?).
Actually, in headless mode, there is no UI, so the manager (which is the UI) is not running. We are running the preview (the stories) in a headless browser.
So we need to collect the metrics in the preview (the iframe or main window) and then send them to the outside (the CI script).
We can do:
- In the preview (the iframe or main window), we measure the metrics and then send them to the main window (if we are in iframe mode) and then the main window (manager) can write them to a file? But in headless mode, the manager is not running.
Alternatively, we can use localStorage or window.name to pass data from the preview to the outside? But in headless mode, we are running Puppeteer and we can read from the page.
So in the CI script:
- Launch Storybook in headless mode (with the addon).
- For each story, we wait for the metrics to be collected (we can have the addon set a global variable on the window or in localStorage).
- Then we read that variable and check against thresholds.
But note: the addon runs in the preview context (iframe or main). We need to expose the metrics to the outside.
Let's design the addon to work in two modes:
- In normal mode (with UI): we show the metrics in the panel.
- In headless mode (without UI): we set a global variable on the window (or in localStorage) with the metrics for the current story, and then the CI script can read that variable.
Steps:
In the addon's preview entry:
import { onStoryReady } from '@storybook/core-events';
import { getMetrics } from './measure';
function measureMetrics() {
const metrics = getMetrics(); // this function uses web-vitals and returns a promise with the metrics
// Then we have to decide where to store them.
// If we are in headless mode (check via environment variable or by the presence of a flag), we store in window.__CWV_METRICS__ = metrics.
// Otherwise, we send to the manager via channel (for UI).
}
onStoryReady(() => {
measureMetrics();
});
But note: the onStoryReady event might fire multiple times? We want to measure for each story.
Actually, we can use the events from @storybook/core-events to listen for story-rendered.
However, the web-vitals metrics are for the entire page load. If we navigate to a new story, the page doesn't reload (in SPA mode). So the metrics might be from the initial load.
This is a problem.
We need to reset the metrics for each story. But web-vitals doesn't reset.
So we cannot measure per story in the same page without reloading.
Therefore, we must reload the page for each story? That would be heavy and not the way Storybook works.
Alternatively, we can measure the metrics for the initial load of the Storybook and then for each story we measure the change? But the metrics are for the page load.
This is a fundamental limitation.
Given this, maybe we cannot measure per story in the same Storybook instance.
We have two options:
Option 1: Run Storybook in a way that each story is loaded in a separate page (like by having a separate URL for each story). Then we can measure the page load for that story.
Storybook by default uses a single page and just swaps the story. So the metrics are for the initial load of Storybook, not for each story.
Option 2: Use the web-vitals library in a way that we measure the component's impact on the metrics after the initial load? But the metrics (LCP, CLS, FID) are about the initial load.
LCP: should happen within the first 2.5s of the page starting to load.
CLS: should not accumulate after the page has loaded (or at least the main accumulation is during load).
FID: should happen during the first interaction.
So if we swap stories without reloading, the metrics for the original page load are still there.
Therefore, to measure per story, we must have a separate page load for each story.
How can we do that?
We can run Storybook in a mode that each story is a separate URL and then we visit each URL separately in the CI and measure the metrics.
In the CI script:
for each story:
visit the story URL (in headless browser)
wait for the metrics to be collected (by the addon)
read the metrics and compare to thresholds.
But note: the addon must be designed to work when the page loads for that story.
So we need to set up the addon to measure on page load and then store the metrics for that page (story) and then the CI script reads them.
How does the addon know which story is being loaded? It can get the story ID from the URL.
Steps for the addon in preview:
- On page load, we measure the metrics (using
web-vitals).
- We get the current story ID from the URL (Storybook puts it in the URL hash or query?).
- We store the metrics in
window.__CWV_METRICS__[storyId] = metrics.
Then the CI script, after visiting the story URL, can read window.__CWV_METRICS__[storyId] from the page.
But note: the CI script needs to wait until the metrics are available.
We can have the addon set a flag when the metrics are ready.
Alternatively, we can have the addon write the metrics to a file (but we are in the browser, so we can't write to the file system).
So we rely on the CI script to read from the page.
Implementation:
In the addon's preview:
import { getStoryIdFromUrl } from './utils'; // we need to get the storyId from the current URL
function measureAndStore() {
getMetrics().then(metrics => {
const storyId = getStoryIdFromUrl();
window.CWV_METRICS = window.CWV_METRICS || {};
window.CWV_METRICS[storyId] = metrics;
});
}
// Run on page load
measureAndStore();
But note: the web-vitals metrics might not be available immediately. We have to wait for them.
The web-vitals library provides a function that returns a promise for each metric, but we have to wait for the ones that are not yet available.
We can use web-vitals's getLCP, getFID, getCLS and wait for all of them.
However, note that some metrics might not be available (if the page didn't have a largest contentful paint, for example). We should handle that.
We'll create a function that returns a promise that resolves when we have all the metrics (or after a timeout).
But note: the web-vitals library's functions (like getLCP) return an object with a value and they fire when the metric is available. We can use Promise.all on the observables? Actually, they return an object with a value and a delta and they are not promises.
We can convert them to promises:
function getMetric(metricFunc) {
return new Promise((resolve) => {
metricFunc((result) => {
resolve(result);
});
});
}
Then:
const [lcp, fid, cls] = await Promise.all([
getMetric(getLCP),
getMetric(getFID),
getMetric(getCLS)
]);
But note: these metrics might take time to be available. We don't want to wait forever.
We can set a timeout, say 10 seconds, and then resolve with whatever we have.
However, the web-vitals library does not provide a way to know if a metric will never be available. We just wait until it fires.
But in a controlled environment (Storybook) we expect all metrics to be available.
Now, for the CI script:
We launch Storybook in headless mode (with the addon).
We generate a list of story URLs (by querying the Storybook index or by using the --ci flag?).
For each story URL:
- Visit the URL in Puppeteer.
- Wait for window.__CWV_METRICS__[storyId] to be set (with a timeout).
- Read the metrics and compare to thresholds.
If any story fails, we exit with error.
How to get the list of story URLs?
We can use the Storybook API to list all stories? Or we can scrape the Storybook index page.
Alternatively, we can run a script that uses the Storybook manager API to get the list of stories and then construct the URLs.
But note: the addon is already running in Storybook, so we can use the Storybook channel to get the list of stories? Not in the preview.
We are in the preview (the page that shows the story). We don't have the list of all stories.
So in the CI, we need to get the list of story URLs from somewhere else.
We can generate the list by:
-
Running npm run storybook -- --ci which might output the list? Not sure.
-
Or we can use the Storybook manager API (which runs in the main window) to get the list of stories. But in headless mode, we are not running the manager? Actually, we are running the entire Storybook (manager and preview) in headless mode.
So we can, in the CI script, after launching Storybook, visit the main page (the Storybook index) and then scrape the story links? That's fragile.
Alternatively, we can have a separate script that uses the Storybook core to list the stories (without launching the server). But that's complex.
Given the complexity, maybe we can change the requirement: instead of blocking merges for every story, we can measure the metrics for the Storybook main page (the index) and then for a set of critical stories (like the ones we specify).
But the requirement says "component usage", so we want to measure each component.
Let's assume we can get the list of story URLs.
We can have a configuration file that lists the story IDs we care about, and then we construct the URLs.
In the CI script:
const storyIds = ['button--primary', 'card--default', ...];
for (const storyId of storyIds) {
const url = http://localhost:6006/iframe.html?id=${storyId}; // if using iframes, the story URL might be different.
// But note: by default, Storybook uses the same page and changes the story via the hash. So the URL for a story is: http://localhost:6006/?path=/story/button--primary
// We can use the ?path= query.
await page.goto(`http://localhost:6006/?path=/story/${storyId}`);
// Wait for the metrics to be set in window.__CWV_METRICS__[storyId]
}
But note: the addon must be loaded and run on that page.
We are launching Storybook with the addon, so it should be.
However, the addon's preview code runs on every page (including the index). We don't want to measure the index, only the stories.
We can check the URL to see if it's a story page (has ?path=/story/).
So in the addon's preview:
if (window.location.search.includes('path=/story/')) {
measureAndStore();
}
Now, the CI script:
We start Storybook (with the addon) on a port.
We have a list of storyIds.
For each storyId, we visit the story URL and then wait for the metrics to be stored.
How do we wait? We can poll for window.__CWV_METRICS__[storyId] or we can have the addon send an event when the metrics are ready? We are in Puppeteer, we can just poll.
Example:
await page.goto(storyUrl);
await page.waitForFunction((storyId) => {
return window.__CWV_METRICS__ && window.__CWV_METRICS__[storyId];
}, storyId, { timeout: 10000 });
Then:
const metrics = await page.evaluate((storyId) => {
return window.__CWV_METRICS__[storyId];
}, storyId);
Then we compare to thresholds.
If any metric is above the threshold, we fail.
But note: the thresholds should be configurable.
We can have a configuration file (like .storybook/cwv-thresholds.json) that the addon reads and the CI script reads.
The addon in preview reads the thresholds and uses them to mark the story as pass/fail (for UI).
The CI script also reads the same thresholds and uses them to fail the build.
Implementation steps for the addon:
-
Create the addon structure.
For Storybook 7, we can use the addon template.
-
The addon will have:
manager.js (for the UI panel) - optional, because in headless we don't need UI.
preview.js (for measuring in the preview).
-
In preview.js:
-
Import web-vitals and the thresholds.
-
Define a function to measure metrics and store in window.__CWV_METRICS__[storyId].
-
Check if we are on a story page (by URL).
-
If so, run the measurement.
-
The thresholds can be read from a file in the project (like .storybook/cwv-thresholds.json). We can fetch it? But in the preview, we are in the browser and the file is in the project, not necessarily served.
We can bundle the thresholds with the addon? Or we can have the user configure the thresholds in the addon's options in .storybook/main.js.
Example in main.js:
addons: [
{
name: 'our-addon',
options: {
thresholds: {
LCP: 2500,
FID: 100,
CLS: 0.1
}
}
}
]
Then in the addon, we can read the options from the Storybook channel? In the preview, we don't have access to the manager's options.
Alternatively, we can set the thresholds in a global variable in the preview by the manager? But we are in the preview, which is a separate context.
We can have the manager send the thresholds to the preview via the channel? That's possible.
But for the CI, we don't have the manager (in headless mode we do run the manager, but we don't need the UI). We can have the CI script read the same configuration from main.js? That's complex.
Alternatively, we can have a separate configuration file that both the addon and the CI script read.
Let's do:
Steps:
In the project, create .storybook/cwv-thresholds.json:
{
"LCP": 2500,
"FID": 100,
"CLS": 0.1
}
Then in the addon's preview:
fetch('/cwv-thresholds.json')
.then(res => res.json())
.then(thresholds => { ... });
But note: the file must be in the static folder of Storybook. By default, Storybook serves the folder.
Given the complexity, we'll start with the addon and then the CI script.
Let's code:
Step 1: Create the addon.
We'll use the Storybook addon template.
Step 2: Implement preview.js:
// src/preview.js
import { addons } from '@storybook/addons';
import { getLCP, getFID, getCLS } from 'web-vitals';
function getStoryId() {
if (window.location.pathname === '/iframe.html') {
const params = new URLSearchParams(window.location.search);
return params.get('id');
} else {
const params = new URLSearchParams(window.location.search);
const path = params.get('path');
if (path && path.startsWith('/story/')) {
return path.replace(/^\/story\//, '');
}
}
return null;
}
function measureMetrics() {
return Promise.all([
new Promise(resolve => getLCP(result => resolve(result))),
new Promise(resolve => getFID(result => resolve(result))),
new Promise(resolve => getCLS(result => resolve(result)))
]).then(([lcp, fid, cls]) => {
return {
LCP: lcp.value,
FID: fid.value,
CLS: cls.value
};
}).catch(error => {
console.error('Error measuring metrics:', error);
return null;
});
}
function storeMetrics(storyId, metrics) {
if (!window.__CWV_METRICS__) {
window.__CWV_METRICS__ = {};
}
window.__CWV_METRICS__[storyId] = metrics;
}
// Check if we are in an iframe (Storybook iframe mode)
const isIframe = window.self !== window.top;
if (!isIframe) {
console.warn('Core Web Vitals Guardrail addon requires iframe mode to measure per-story metrics. Please enable iframe mode in Storybook configuration.');
return;
}
const storyId = getStoryId();
if (storyId) {
measureMetrics().then(metrics => {
if (metrics) {
storeMetrics(storyId, metrics);
// Also emit to manager via channel
const channel = addons.getChannel();
channel.emit('cwx/metrics', { storyId, metrics });
}
});
}
Step 3: Implement manager.js:
// src/manager.js
import { addons } from '@storybook/addons';
const channel = addons.getChannel();
// Initialize the store in the manager window
window.__CWV_METRICS_MANAGER__ = {};
channel.on('cwx/metrics', (data) => {
window.__CWV_METRICS_MANAGER__[data.storyId] = data.metrics;
});
Step 4: Implement panel.js (React component):
// src/Panel.js
import React, { useEffect, useState } from 'react';
import { useStorybookState } from '@storybook/client-api';
import { useAddonState } from '@storybook/addons';
import { AddonPanel } from '@storybook/components';
{ Sticky, Table, TableBody, TableCell, TableHeader, TableHeaderCell, TableRow } from '@storybook/components';
const thresholds = {
LCP: 2500,
FID: 100,
CLS: 0.1
};
export const Panel = () => {
const { storyId } = useStorybookState();
const [metrics, setMetrics] = useState(null);
useEffect(() => {
// Read from the global store set by manager.js
const store = window.__CWV_METRICS_MANAGER__;
if (store && storyId && store[storyId]) {
setMetrics(store[storyId]);
}
}, [storyId]);
if (!metrics) {
return <div>No metrics available yet.</div>;
}
const passed = metrics.LCP <= thresholds.LCP && metrics.FID <= thresholds.FID && metrics.CLS <= thresholds.CLS;
return (
<AddonPanel title="Core Web Vitals">
<Sticky>
<Table>
<TableHeader>
<TableRow>
<TableHeaderCell>Metric</TableHeaderCell>
<TableHeaderCell>Value (ms/unit)</TableHeaderCell>
<TableHeaderCell>Threshold</TableHeaderCell>
<TableHeaderCell>Status</TableHeaderCell>
</TableRow>
</TableHeader>
<TableBody>
<TableRow key="LCP">
<TableCell>LCP</TableCell>
<TableCell>{metrics.LCP} ms</TableCell>
<TableCell>{thresholds.LCP} ms</TableCell>
<TableCell style={{ color: metrics.LCP <= thresholds.LCP ? 'green' : 'red' }}>
{metrics.LCP <= thresholds.LCP ? 'PASS' : 'FAIL'}
</TableCell>
</TableRow>
<TableRow key="FID">
<TableCell>FID</TableCell>
<TableCell>{metrics.FID} ms</TableCell>
<TableCell>{thresholds.FID} ms</TableCell>
<TableCell style={{ color: metrics.FID <= thresholds.FID ? 'green' : 'red' }}>
{metrics.FID <= thresholds.FID ? 'PASS' : 'FAIL'}
</TableCell>
</TableRow>
<TableRow key="CLS">
<TableCell>CLS</TableCell>
<TableCell>{metrics.CLS}</TableCell>
<TableCell>{thresholds.CLS}</TableCell>
<TableCell style={{ color: metrics.CLS <= thresholds.CLS ? 'green' : 'red' }}>
{metrics.CLS <= thresholds.CLS ? 'PASS' : 'FAIL'}
</TableCell>
</TableRow>
</TableBody>
</Table>
<div style={{ marginTop: '10px', fontWeight: 'bold', color: passed ? 'green' : 'red' }}>
Overall: {passed ? 'PASS' : 'FAIL'}
</div>
</Sticky>
</AddonPanel>
);
};
Step 5: Register the addon in src/manager.js and src/preview.js and src/Panel.js in register.js:
// src/register.js
import { Panel } from './Panel';
export const parameters = {
// ... other parameters
};
export const preview = {
// ... other preview
};
export const manager = {
// ... other manager
};
export const addon = {
name: 'Core Web Vitals Guardrail',
type: 'panel',
paramKey: 'cwx',
panel: Panel,
// ... other addon config
};
But note: the addon type is 'panel', and we are providing a panel.
Actually, the addon structure in Storybook 7 is different. We have:
export default {
title: 'Core Web Vitals Guardrail',
parameters: {},
// This is for the preview
preview: {
// ...
},
// This is for the manager
manager: {
// ...
},
};
And we also have the panel component.
Alternatively, we can use the new addon structure:
// In the main file (index.js) of the addon:
export const __docgenInfo = {
description: 'Core Web Vitals Guardrail addon',
};
export const parameters = {};
export const preview = async (...args) => {
// ... preview code
};
export const manager = async (...args) => {
// ... manager code
};
But let's follow the template.
Given the complexity, I think we have a plan.
Now, the CI script:
// scripts/check-cwx.js
const puppeteer = require('puppeteer');
const fs = require('fs');
const path = require('path');
const STORYBOOK_URL = 'http://localhost:6006';
const STORIES_CONFIG_PATH = path.join(__dirname, '../.storybook/stories-to-check.json');
const THRESHOLDS_PATH = path.join(__dirname, '../.storybook/public/cwv-thresholds.json');
async function run() {
// Start Storybook
const storybookProcess = require('child_process').spawn('npx', ['storybook', 'dev', '--ci', '--port', '6006'], {
stdio: 'inherit',
shell: true
});
// Wait for Storybook to be ready
await new Promise(resolve => setTimeout(resolve, 10000)); // wait 10 seconds, or we can poll the URL
const browser = await puppeteer.launch();
const page = await browser.newPage();
const stories = JSON.parse(fs.readFileSync(STORIES_CONFIG_PATH, 'utf8')).stories;
const thresholds = JSON.parse(fs.readFileSync(THRESHOLDS_PATH, 'utf8'));
let hasFailure = false;
for (const storyId of stories) {
const storyUrl = `${STORYBOOK_URL}/?path=/story/${storyId}`;
console.log(`Checking story: ${storyId} at ${storyUrl}`);
try {
await page.goto(storyUrl, { waitUntil: 'networkidle0' });
// Wait for the iframe
await page.waitForSelector('iframe[title="Story"]', { timeout: 5000 });
// Get the iframe
const frames = page.frames();
const storyFrame = frames.find(frame => frame.url().includes('iframe.html?id='));
if (!storyFrame) {
throw new Error('Story iframe not found');
}
// Wait for the metrics to be set in the iframe
await storyFrame.waitForFunction(() => {
return window.__CWV_METRICS__ && window.__CWV_METRICS__[window.__CWV_STORY_ID__];
}, { timeout: 10000 });
const metrics = await storyFrame.evaluate(() => {
const storyId = window.__CWV_STORY_ID__;
return window.__CWV_METRICS__[storyId];
});
if (!metrics) {
throw new Error('Metrics not found in iframe');
}
// Check thresholds
const lcpPass = metrics.LCP <= thresholds.LCP;
const fidPass = metrics.FID <= thresholds.FID;
const clsPass = metrics.CLS <= thresholds.CLS;
if (!lcpPass || !fidPass || !clsPass) {
hasFailure = true;
console.error(`Story ${storyId} failed:`);
if (!lcpPass) console.error(` LCP: ${metrics.LCP}ms (threshold: ${thresholds.LCP}ms)`);
if (!fidPass) console.error(` FID: ${metrics.FID}ms (threshold: ${thresholds.FID}ms)`);
if (!clsPass) console.error(` CLS: ${metrics.CLS} (threshold: ${thresholds.CLS})`);
} else {
console.log(`Story ${storyId} passed.`);
}
} catch (error) {
hasFailure = true;
console.error(`Error checking story ${storyId}:`, error.message);
}
}
await browser.close();
storybookProcess.kill();
if (hasFailure) {
console.error('Core Web Vitals check failed for one or more stories.');
process.exit(1);
} else {
console.log('All stories passed Core Web Vitals check.');
process.exit(0);
}
}
run().catch(console.error);
Step 6: We must also kill the Storybook process when done.
Step 7: We must handle the case where Storybook fails to start.
Step 8: We must make the script robust.
This is a basic version.
Now, we have:
- An addon that measures CWV in iframe mode and displays in a panel.
- A CI script that runs the check and fails if any story is above thresholds.
We also require:
- iframe mode enabled in Storybook.
- The thresholds file and stories-to-check file in place.
We can improve:
- Make the addon work without iframe mode? We can try to measure in non-iframe mode by reloading the page for each story? But that would be very slow and not the way Storybook works.
- Instead, we can have the addon measure the metrics for the current story by using the `web-vitals` library and then subtracting the baseline? But that's not accurate.
So we require iframe mode.
Let's update the addon to show a warning if not in iframe mode.
And in the CI script, we can check if the iframe is present and fail if not.
We can also have the CI script check the Storybook configuration to see if iframe mode is enabled? But that's complex.
We'll just rely on the user to enable iframe mode.
Now, we must document the setup:
- Enable iframe mode in `.storybook/main.js`:
framework: {
name: '@storybook/react-webpack5', // or whatever
options: {
iframe: 'strict'
}
}
- Create `.storybook/public/cwv-thresholds.json` with the thresholds.
- Create `.storybook/stories-to-check.json` with the list of story IDs.
- Run the addon in Storybook (dev mode) to see the panel.
- Run the CI script in the CI pipeline.
We can also make the CI script part of the addon? We can provide an npm script that runs the check.
We can also have the addon block the merge by failing the CI.
This is a high-level design and implementation.
We must also consider that the web-vitals library might not be available in the iframe? We are bundling it with the addon, so it should be.
We must also consider that the iframe might be from a different origin? But Storybook serves everything from the same origin.
So we are good.
Let's code the addon and the CI script.
However, note that the addon's preview code runs in the iframe, and we are importing web-vitals and the thresholds. We must make sure the thresholds are available in the iframe.
We put the thresholds in the public folder, so they are served by Storybook. But the iframe is a separate document, and it can fetch the thresholds? We are importing the thresholds as a JSON module, so it's bundled.
So we don't need to fetch the thresholds in the iframe; we can import them.
But we want the same thresholds in the CI script, so we put the file in the public folder and also require it in the CI script.
We can do:
In the addon, we import the thresholds from a path relative to the addon's code? But the addon is built and then the thresholds are in the public folder of Storybook.
We can have the addon read the thresholds from a file that we copy to the public folder? But we are developing the addon separately.
Alternatively, we can have the thresholds as part of the addon's options? Then the user configures the thresholds in `main.js` and we pass them to the addon.
Then the addon uses the options for the panel and for the measurement? But the measurement is in the iframe, and the options are in the manager. We need to send the thresholds to the iframe.
We can have the manager send the thresholds to the iframe via the channel? Then the iframe can use them.
But then we have to wait for the thresholds to be sent? The iframe loads before the manager? We can have the iframe wait for the thresholds.
This is getting complex.
Let's stick to having the thresholds in a file that is served by Storybook and both the addon and the CI script read from that file.
We can put the thresholds in `.storybook/public/cwv-thresholds.json` and then:
In the addon's preview, we fetch that file? But we are in the iframe, and the file is at the main Storybook origin, so we can fetch it.
But we are building the addon, and we don't want to fetch at runtime? We can bundle the thresholds with the addon? But then the user cannot change them without rebuilding.
We want the user to configure the thresholds without rebuilding.
So we must fetch the thresholds at runtime.
In the addon's preview:
fetch('/cwv-thresholds.json')
.then(res => res.json())
.then(thresholds => {
// use thresholds
});
But then we have to wait for the fetch before measuring? We can measure with default thresholds and then when we get the thresholds, we compare? But the metrics are already measured.
Alternatively, we can measure after we get the thresholds? But the metrics are about the page load, and we might miss them.
So we must measure immediately when the page loads, and then when we get the thresholds, we compare.
We can store the metrics without comparing, and then when we get the thresholds, we compare and send the result.
But then the panel might show the metrics and then later update the status.
This is acceptable.
Steps:
- On page load, we measure the metrics and store them (without thresholds).
- We fetch the thresholds.
- When we have both, we compare and then store the passed status.
But note: the CI script doesn't need the thresholds from the file because it reads the same file. So we are consistent.
So in the iframe:
let metrics = null;
let thresholds = null;
measureMetrics().then(m => {
metrics = m;
if (thresholds) {
storeMetrics(storyId, { metrics, thresholds });
}
});
fetch('/cwv-thresholds.json').then(res => res.json()).then(t => {
thresholds = t;
if (metrics) {
storeMetrics(storyId, { metrics, thresholds });
}
});
Then we store an object with both.
Then in the panel, we can compute the passed status.
In the CI script, we read the thresholds from the file and then compare with the metrics.
This works.
However, the CI script doesn't need the thresholds from the iframe; it reads the same file. So we can just store the metrics in the iframe and let the CI script read the thresholds from the file.
But in the panel, we want to show the thresholds and the status. So we need the thresholds in the manager.
We can have the iframe send the thresholds to the manager? Or we can have the manager read the thresholds from the same file? The manager doesn't have access to the file system.
So we must fetch the thresholds in the manager? We can fetch from the same URL (/cwv-thresholds.json).
In the manager:
fetch('/cwv-thresholds.json')
.then(res => res.json())
.then(thresholds => {
window.__CWV_THRESHOLDS__ = thresholds;
});
Then the panel can read window.__CWV_THRESHOLDS__.
But note: the manager and the panel are in the same window, so we can set a global.
Alternatively, we can have the iframe send the thresholds to the manager via the channel? But the thresholds are the same for all stories.
Let's do:
In the manager:
fetch('/cwv-thresholds.json')
.then(res => res.json())
.then(thresholds => {
window.__CWV_THRESHOLDS__ = thresholds;
});
In the iframe:
We only store the metrics (without thresholds). We don't need thresholds in the iframe.
Then the panel uses `window.__CWV_THRESHOLDS__` and the metrics from `window.__CWV_METRICS_MANAGER__` to compute the status.
But the CI script reads the thresholds from the file and the metrics from the iframe.
This is acceptable.
Let's adjust:
In preview (iframe):
We only store the metrics in `window.__CWV_METRICS__[storyId] = metrics;` (just the metrics object with LCP, FID, CLS).
We don't store thresholds.
In manager:
We fetch the thresholds and store in `window.__CWV_THRESHOLDS__`.
We also store the metrics from the iframe in `window.__CWV_METRICS_MANAGER__[storyId]`.
In panel:
const thresholds = window.__CWV_THRESHOLDS__;
const metrics = window.__CWV_METRICS_MANAGER__?.[storyId];
Then compute passed.
But note: the thresholds might not be loaded yet when the panel first renders. We can use state and update when thresholds are loaded.
We can have the manager set the thresholds and then the panel can read from the global. But we cannot trigger a re-render when the global changes.
We can use a custom event? Or we can have the panel poll? Or we can have the manager send the thresholds via the channel to the panel? But the panel is a React component and we can use state.
Alternatively, we can have the panel read the thresholds from the global on every render? That's not efficient but it's a small object.
We can do:
const thresholds = window.__CWV_THRESHOLDS__ || {};
And then when the thresholds are set, the panel will re-render because the storyId changes? Not necessarily.
We can use an interval to check for thresholds? That's hacky.
Better: the manager, when it loads the thresholds, can emit an event on the channel that the thresholds are loaded, and the panel can listen and update its state.
Let's do:
In manager:
fetch('/cwv-thresholds.json')
.then(res => res.json())
.then(thresholds => {
window.__CWV_THRESHOLDS__ = thresholds;
const channel = addons.getChannel();
channel.emit('cwx/thresholds', thresholds);
});
In panel:
const [thresholds, setThresholds] = useState({});
useEffect(() => {
const channel = addons.getChannel();
channel.on('cwx/thresholds', setThresholds);
// Also check if thresholds are already loaded
if (window.__CWV_THRESHOLDS__) {
setThresholds(window.__CWV_THRESHOLDS__);
}
}, []);
Then we have the thresholds in state.
Now, the panel uses thresholds state and metrics from the global store (or we can also use state for metrics and update via channel?).
We can do the same for metrics:
In manager, when we receive metrics from the iframe, we store in the global and emit an event.
But the panel is only interested in the current story's metrics.
We can have the panel listen for `cwx/metrics` and then update the metrics for the current story.
But we are already storing in the global. We can just read from the global and then when the global changes, we update? But React doesn't know when the global changes.
We can use a state for metrics and update it when the channel event comes for the current story.
Alternatively, we can have the panel read the metrics from the global on every render? That's acceptable because the metrics are set once per story.
Let's do:
In panel:
const { storyId } = useStorybookState();
const [thresholds, setThresholds] = useState({});
const [metrics, setMetrics] = useState(null);
useEffect(() => {
const channel = addons.getChannel();
// Load thresholds
channel.on('cwx/thresholds', setThresholds);
if (window.__CWV_THRESHOLDS__) {
setThresholds(window.__CWV_THRESHOLDS__);
}
// We don't need to listen for metrics because we read from global and the storyId changes.
// But we want to update when the metrics for the current story are set.
// We can poll? Or we can have the manager emit an event for the current story?
// Let's have the manager emit an event for every metrics update, and then in the panel, we check if it's for the current story.
channel.on('cwx/metrics', (data) => {
if (data.storyId === storyId) {
setMetrics(data.metrics);
}
});
// Also, if the metrics are already in the global for the current story, set them.
if (window.__CWV_METRICS_MANAGER__ && window.__CWV_METRICS_MANAGER__[storyId]) {
setMetrics(window.__CWV_METRICS_MANAGER__[storyId]);
}
}, [storyId]);
Then we have metrics and thresholds in state.
This is better.
Now, the panel will update when the thresholds are loaded and when the metrics for the current story are set.
We must also handle the case where the story changes and the metrics for the new story are already in the global? We read from the global in the effect when storyId changes.
So it should work.
Now, let's adjust the manager:
In manager.js:
import { addons } from '@storybook/addons';
const channel = addons.getChannel();
window.__CWV_METRICS_MANAGER__ = {};
channel.on('cwx/metrics', (data) => {
window.__CWV_METRICS_MANAGER__[data.storyId] = data.metrics;
// Also emit to the panel? The panel is listening on the same channel, so it will get the event.
});
// Load thresholds
fetch('/cwv-thresholds.json')
.then(res => res.json())
.then(thresholds => {
window.__CWV_THRESHOLDS__ = thresholds;
channel.emit('cwx/thresholds', thresholds);
});
And in the iframe (preview.js) we only emit the metrics (without thresholds).
This should work.
Now, the CI script:
We don't need to wait for the thresholds because we read them from the file.
We wait for the metrics in the iframe.
We are done.
Let's write the code accordingly.
However, note that the iframe might be from a different origin? No, it's the same origin.
We are good.
We must also consider that the iframe might not have window.__CWV_METRICS__ if the measurement failed. We handle that by timing out.
We must also consider that the iframe might be loading other resources and the web-vitals might not have fired yet. We wait for 10 seconds.
This should be enough.
Now, we have a plan and code structure.
We must also write tests? Maybe later.
We must also document.
This is a complex addon.
Let me know if you have any questions.
I'll help you engineering a Core Web Vitals guardrail system for Storybook that prevents merges when component usage degrades performance metrics. This solution combines Storybook addon development with CI/CD integration.
Architecture Overview
┌─────────────────┐ ┌──────────────────┐ ┌──────────────┐
│ Storybook │ │ Performance │ │ CI/CD │
│ (Dev Mode) │────► Monitor │────► Pipeline │
│ │ │ (Web Vitals) │ │ (Gate) │
└─────────────────┘ └──────────────────┘ └──────────────┘
▲ │ │
│ ▼ ▼
┌─────────────────┐ ┌──────────────────┐ ┌──────────────┐
│ Storybook │ │ Threshold │ │ Merge │
│ Addon Panel │◄───┤ Config │◄───┤ Block │
│ │ │ │ │ │
└─────────────────┘ └──────────────────┘ └──────────────┘
1. Storybook Addon Implementation
Installation
npm install --save-dev @storybook/addon-web-vitals-guardrail
# or
yarn add -D @storybook/addon-web-vitals-guardrail
Core Addon Files
src/preview.js - Metrics collection in iframe context:
import { getLCP, getFID, getCLS, getFCP, getTTFB } from 'web-vitals';
// Store metrics per storyId
const storyMetrics = new Map();
// Thresholds (can be configured)
const DEFAULT_THRESHOLDS = {
LCP: 2500, // ms
FID: 100, // ms
CLS: 0.1, // score
FCP: 1800, // ms
TTFB: 800, // ms
};
// Get current story ID from URL
function getCurrentStoryId() {
const params = new URLSearchParams(window.location.search);
return params.get('path')?.replace(/^\/story\//, '') || 'unknown';
}
// Measure all web vitals
async function measureWebVitals() {
const metrics = {};
await Promise.all([
new Promise(resolve => getLCP(result => { metrics.LCP = result.value; resolve(); })),
new Promise(resolve => getFID(result => { metrics.FID = result.value; resolve(); })),
new Promise(resolve => getCLS(result => { metrics.CLS = result.value; resolve(); })),
new Promise(resolve => getFCP(result => { metrics.FCP = result.value; resolve(); })),
new Promise(resolve => getTTFB(result => { metrics.TTFB = result.value; resolve(); })),
]);
return metrics;
}
// Main collection function
export async function collectMetrics() {
const storyId = getCurrentStoryId();
try {
const metrics = await measureWebVitals();
const thresholds = window.__CWV_THRESHOLDS__ || DEFAULT_THRESHOLDS;
// Calculate scores
const scores = {
LCP: metrics.LCP <= thresholds.LCP ? 'good' :
metrics.LCP <= thresholds.LCP * 1.5 ? 'needs-improvement' : 'poor',
FID: metrics.FID <= thresholds.FID ? 'good' : 'poor',
CLS: metrics.CLS <= thresholds.CLS ? 'good' : 'poor',
FCP: metrics.FCP <= thresholds.FCP ? 'good' :
metrics.FCP <= thresholds.FCP * 1.5 ? 'needs-improvement' : 'poor',
TTFB: metrics.TTFB <= thresholds.TTFB ? 'good' : 'poor',
};
const result = {
storyId,
metrics,
thresholds,
scores,
timestamp: Date.now(),
passed: Object.values(scores).every(s => s === 'good'),
url: window.location.href,
};
storyMetrics.set(storyId, result);
// Send to manager window
if (window.parent !== window) {
window.parent.postMessage({
type: 'CWV_METRICS_UPDATE',
payload: result
}, '*');
}
return result;
} catch (error) {
console.error('Failed to collect CWV metrics:', error);
return null;
}
}
// Auto-collect on story render
export function setupAutoCollection() {
// Wait for story to render
const observer = new MutationObserver(() => {
if (document.querySelector('[data-story-id]')) {
setTimeout(collectMetrics, 1000); // Wait for layout to settle
}
});
observer.observe(document.body, {
childList: true,
subtree: true
});
}
// Expose for manual triggering
window.__CWV_COLLECT__ = collectMetrics;
window.__CWV_STORY_METRICS__ = storyMetrics;
src/manager.js - Manager-side metrics handling:
import { addons, useChannel, useEffect, useState } from '@storybook/addons';
import { STORY_CHANGED } from '@storybook/core-events';
const channel = addons.getChannel();
const metricsStore = new Map();
// Listen for metrics from preview iframes
window.addEventListener('message', (event) => {
if (event.data.type === 'CWV_METRICS_UPDATE') {
const { storyId, ...metrics } = event.data.payload;
metricsStore.set(storyId, metrics);
// Save to localStorage for persistence
try {
const allMetrics = JSON.parse(localStorage.getItem('cwx-metrics') || '{}');
allMetrics[storyId] = metrics;
localStorage.setItem('cwx-metrics', JSON.stringify(allMetrics));
} catch (e) {
console.warn('Failed to persist metrics:', e);
}
}
});
// Load persisted metrics
try {
const persisted = JSON.parse(localStorage.getItem('cwx-metrics') || '{}');
Object.entries(persisted).forEach(([storyId, metrics]) => {
metricsStore.set(storyId, metrics);
});
} catch (e) {
console.warn('Failed to load persisted metrics:', e);
}
// Export for panel
export { metricsStore, channel };
src/panel/WebVitalsPanel.js - UI panel component:
import React, { useEffect, useState } from 'react';
import { useStorybookState, useAddonState } from '@storybook/addons';
import { AddonPanel } from '@storybook/components';
import { StyledTable, StyledTableCell, StyledTableHeader, StyledTableRow } from '@storybook/components';
import {InfoIcon} from '@storybook/client-api';
const STATUS_COLORS = {
good: '#10b981',
'needs-improvement': '#f59e0b',
poor: '#ef4444'
};
const STATUS_LABELS = {
good: 'PASS',
'needs-improvement': 'WARNING',
poor: 'FAIL'
};
export const WebVitalsPanel = () => {
const { storyId } = useStorybookState();
const [metrics, setMetrics] = useState(null);
const [thresholds, setThresholds] = useState({});
useEffect(() => {
// Get current story metrics
const currentMetrics = window.__CWV_METRICS_MANAGER__?.get?.(storyId);
if (currentMetrics) {
setMetrics(currentMetrics);
setThresholds(currentMetrics.thresholds);
}
}, [storyId]);
if (!metrics) {
return (
<AddonPanel title="Core Web Vitals">
<div style={{ padding: '20px', textAlign: 'center' }}>
<p>No metrics collected yet.</p>
<p>Metrics are collected after story renders.</p>
<button
onClick={() => window.__CWV_COLLECT__?.()}
style={{ padding: '8px 16px', marginTop: '10px' }}
>
Collect Now
</button>
</div>
</AddonPanel>
);
}
const allPassed = metrics.passed;
return (
<AddonPanel title="Core Web Vitals">
<div style={{ padding: '16px' }}>
<div style={{
padding: '12px',
borderRadius: '6px',
marginBottom: '16px',
backgroundColor: allPassed ? '#dcfce7' : '#fee2e2',
border: `1px solid ${allPassed ? '#86efac' : '#fca5a5'}`
}}>
<strong>Overall Status: </strong>
<span style={{ color: allPassed ? '#166534' : '#991b1b', marginLeft: '8px' }}>
{allPassed ? '✅ PASS' : '❌ FAIL'}
</span>
</div>
<StyledTable>
<thead>
<StyledTableRow>
<StyledTableHeader>Metric</StyledTableHeader>
<StyledTableHeader>Value</StyledTableHeader>
<StyledTableHeader>Threshold</StyledTableHeader>
<StyledTableHeader>Status</StyledTableHeader>
</StyledTableRow>
</thead>
<tbody>
{Object.entries(metrics.metrics).map(([key, value]) => {
const threshold = thresholds[key];
const status = metrics.scores[key];
return (
<StyledTableRow key={key}>
<StyledTableCell>{key}</StyledTableCell>
<StyledTableCell>
{key === 'CLS' ? value.toFixed(3) : `${Math.round(value)}ms`}
</StyledTableCell>
<StyledTableCell>
{key === 'CLS' ? threshold.toFixed(3) : `${threshold}ms`}
</StyledTableCell>
<StyledTableCell>
<span style={{
color: STATUS_COLORS[status],
fontWeight: 'bold',
padding: '2px 8px',
borderRadius: '4px',
backgroundColor: STATUS_COLORS[status] + '20'
}}>
{STATUS_LABELS[status]}
</span>
</StyledTableCell>
</StyledTableRow>
);
})}
</tbody>
</StyledTable>
<div style={{ marginTop: '20px', fontSize: '12px', color: '#666' }}>
<p><InfoIcon /> Metrics collected: {new Date(metrics.timestamp).toLocaleTimeString()}</p>
<p><InfoIcon /> Story: {metrics.storyId}</p>
</div>
</div>
</AddonPanel>
);
};
src/register.js - Addon registration:
export const __docgenInfo = {
description: 'Core Web Vitals Guardrail - Blocks merges when components degrade performance',
};
export const preview = async ({ config, options }) => {
// Inject thresholds from options or defaults
window.__CWV_THRESHOLDS__ = options.thresholds || {
LCP: 2500,
FID: 100,
CLS: 0.1,
FCP: 1800,
TTFB: 800,
};
// Auto-collect setup
if (options.autoCollect !== false) {
const { setupAutoCollection } = await import('./preview');
setupAutoCollection();
}
return {
// This will be available in preview iframes
__CWV_COLLECT__: window.__CWV_COLLECT__,
};
};
export const manager = async () => {
const { metricsStore, channel } = await import('./manager');
return {
// Make available to panel
__CWV_METRICS_MANAGER__: metricsStore,
__CWV_CHANNEL__: channel,
};
};
export const parameters = {
cwx: {
title: 'Web Vitals',
icon: 'speed',
category: 'Quality',
showPanel: true,
},
};
Configuration in .storybook/main.js:
module.exports = {
addons: [
{
name: '@storybook/addon-web-vitals-guardrail',
options: {
// Custom thresholds (optional)
thresholds: {
LCP: 2000, // ms
FID: 50, // ms
CLS: 0.05, // score
FCP: 1500, // ms
TTFB: 600, // ms
},
// Auto-collect on story render (default: true)
autoCollect: true,
},
},
],
framework: {
name: '@storybook/react-webpack5',
options: {
// Required for iframe-based measurement
iframe: 'strict', // or 'shared' for shared iframe
},
},
};
2. CI/CD Integration (GitHub Actions Example)
.github/workflows/cwx-gate.yml:
name: Core Web Vitals Gate
on:
pull_request:
branches: [main, develop]
jobs:
cwx-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
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: Start Storybook (headless)
run: npx http-server storybook-static -p 6006 &
env:
CI: true
- name: Wait for Storybook
run: |
for i in {1..30}; do
if curl -s http://localhost:6006 > /dev/null; then
echo "Storybook is ready"
break
fi
sleep 2
done
- name: Run CWV Gate Check
run: |
node scripts/cwx-gate.js \
--storybook-url http://localhost:6006 \
--stories-config .storybook/stories-to-check.json \
--thresholds .storybook/cwv-thresholds.json \
--fail-on-warnings false
- name: Comment PR with results
if: always()
uses: thollander/actions-comment-pull-request@v2
with:
message: |
## Core Web Vitals Check Results
${{ steps.cwx-check.outputs.results }}
scripts/cwx-gate.js - CI script:
#!/usr/bin/env node
const puppeteer = require('puppeteer');
const fs = require('fs');
const path = require('path');
const { program } = require('commander');
program
.option('--storybook-url <url>', 'Storybook URL', 'http://localhost:6006')
.option('--stories-config <path>', 'Stories config JSON path')
.option('--thresholds <path>', 'Thresholds JSON path')
.option('--fail-on-warnings', 'Fail on needs-improvement', false)
.parse();
const options = program.opts();
async function runCheck() {
const browser = await puppeteer.launch({
headless: 'new',
args: ['--no-sandbox', '--disable-setuid-sandbox']
});
const page = await browser.newPage();
// Load thresholds
const thresholds = JSON.parse(fs.readFileSync(options.thresholds, 'utf8'));
// Load stories to check
const { stories } = JSON.parse(fs.readFileSync(options.storiesConfig, 'utf8'));
const results = {
passed: [],
failed: [],
warnings: [],
errors: []
};
for (const story of stories) {
try {
console.log(`\n📋 Checking story: ${story.id}`);
// Navigate to story
const url = `${options.storybookUrl}/?path=/story/${story.id}`;
await page.goto(url, { waitUntil: 'networkidle0', timeout: 30000 });
// Wait for iframe to load
await page.waitForSelector('iframe[title="Story"]', { timeout: 10000 });
// Get iframe
const frame = page
.frames()
.find(f => f.url().includes('iframe.html?id='));
if (!frame) {
throw new Error('Story iframe not found');
}
// Wait for metrics to be collected
await frame.waitForFunction(() => {
return window.__CWV_METRICS__?.[window.__CWV_STORY_ID__];
}, { timeout: 15000 });
// Get metrics from iframe
const metricsData = await frame.evaluate(() => {
const storyId = window.__CWV_STORY_ID__;
return window.__CWV_METRICS__?.[storyId];
});
if (!metricsData) {
throw new Error('Metrics not found in iframe');
}
// Check against thresholds
const checks = {
LCP: metricsData.metrics.LCP <= thresholds.LCP,
FID: metricsData.metrics.FID <= thresholds.FID,
CLS: metricsData.metrics.CLS <= thresholds.CLS,
FCP: metricsData.metrics.FCP <= thresholds.FCP,
TTFB: metricsData.metrics.TTFB <= thresholds.TTFB,
};
const failedChecks = Object.entries(checks).filter(([_, passed]) => !passed);
const hasWarnings = Object.entries(metricsData.scores).some(([_, status]) =>
status === 'needs-improvement'
);
if (failedChecks.length === 0 && !hasWarnings) {
results.passed.push({ id: story.id, ...metricsData });
console.log(` ✅ PASSED`);
} else if (options.failOnWarnings && hasWarnings) {
results.warnings.push({
id: story.id,
warnings: Object.entries(metricsData.scores)
.filter(([_, status]) => status === 'needs-improvement')
.map(([metric]) => metric)
});
console.log(` ⚠️ WARNING: ${story.id} has needs-improvement metrics`);
} else {
results.failed.push({
id: story.id,
checks: failedChecks.map(([metric]) => metric),
metrics: metricsData.metrics
});
console.log(` ❌ FAILED: ${failedChecks.map(([m]) => m).join(', ')}`);
}
} catch (error) {
results.errors.push({ id: story.id, error: error.message });
console.log(` ❌ ERROR: ${error.message}`);
}
}
await browser.close();
// Generate report
const report = generateReport(results, thresholds);
console.log('\n' + report);
// Exit with appropriate code
const hasFailures = results.failed.length > 0 ||
(options.failOnWarnings && results.warnings.length > 0) ||
results.errors.length > 0;
process.exit(hasFailures ? 1 : 0);
}
function generateReport(results, thresholds) {
let report = '## Core Web Vitals Gate Report\n\n';
report += `### Summary\n`;
report += `- ✅ Passed: ${results.passed.length}\n`;
report += `- ⚠️ Warnings: ${results.warnings.length}\n`;
report += `- ❌ Failed: ${results.failed.length}\n`;
report += `- ❌ Errors: ${results.errors.length}\n\n`;
if (results.failed.length > 0) {
report += '### Failed Stories\n';
results.failed.forEach(({ id, checks, metrics }) => {
report += `\n**${id}**\n`;
checks.forEach(([metric, _]) => {
report += `- ${metric}: ${metrics[metric].toFixed(1)} (threshold: ${thresholds[metric]})\n`;
});
});
}
if (results.warnings.length > 0) {
report += '\n### Stories with Warnings\n';
results.warnings.forEach(({ id, warnings }) => {
report += `\n**${id}** - ${warnings.join(', ')}\n`;
});
}
if (results.errors.length > 0) {
report += '\n### Errors\n';
results.errors.forEach(({ id, error }) => {
report += `\n**${id}** - ${error}\n`;
});
}
report += `\n### Thresholds Used\n`;
Object.entries(thresholds).forEach(([metric, value]) => {
report += `- ${metric}: ${value}\n`;
});
return report;
}
runCheck().catch(console.error);
/.storybook/stories-to-check.json - Stories configuration:
{
"stories": [
{ "id": "components-button--primary", "critical": true },
{ "id": "components-button--secondary", "critical": true },
{ "id": "components-card--default", "critical": false },
{ "id": "components-navbar--main", "critical": true },
{ "id": "components-modal--base", "critical": false }
],
"options": {
"onlyCritical": false,
"excludePatterns": ["**/tests/**", "**/deprecated/**"]
}
}
/.storybook/cwv-thresholds.json - Threshold configuration:
{
"LCP": 2500,
"FID": 100,
"CLS": 0.1,
"FCP": 1800,
"TTFB": 800,
"strictMode": {
"LCP": 2000,
"FID": 50,
"CLS": 0.05
}
}
3. Package.json Scripts
{
"scripts": {
"cwx:check": "node scripts/cwx-gate.js",
"cwx:dev": "storybook dev --ci",
"cwx:build": "storybook build",
"cwx:review": "npm run cwx:build && npm run cwx:check",
"cwx:pr-review": "npm run cwx:dev & sleep 10 && npm run cwx:check"
}
}
4. Pre-commit Hook (Optional)
.husky/pre-commit:
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
# Run Storybook in headless mode and check CWV
echo "🔍 Running Core Web Vitals check..."
npx storybook build --quiet
# Run gate check against built Storybook
npx http-server storybook-static -p 6006 &
STORYBOOK_PID=$!
sleep 10
node scripts/cwx-gate.js \
--storybook-url http://localhost:6006 \
--stories-config .storybook/stories-to-check.json \
--thresholds .storybook/cwv-thresholds.json
kill $STORYBOOK_PID 2>/dev/null
5. GitHub PR Comment Bot
.github/workflows/cwx-comment.yml:
name: CWV PR Comments
on:
pull_request:
paths:
- 'src/components/**'
jobs:
comment:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Install and run CWV check
run: |
npm ci
npm run build-storybook
npx http-server storybook-static -p 6006 &
sleep 10
RESULTS=$(node scripts/cwx-gate.js --storybook-url http://localhost:6006)
echo "RESULTS<<EOF"$'\n'"$RESULTS"$'\n'"EOF" >> $GITHUB_ENV
- name: Comment PR
uses: thollander/actions-comment-pull-request@v2
with:
message: |
## 🚦 Core Web Vitals Performance Report
${{ env.RESULTS }}
**Note**: This check runs against component examples in Storybook.
Ensure your changes don't degrade performance metrics.
6. Advanced Features
A. Dynamic Thresholds by Device
{
"thresholds": {
"mobile": {
"LCP": 2500,
"FID": 100,
"CLS": 0.1
},
"desktop": {
"LCP": 4000,
"FID": 150,
"CLS": 0.1
}
}
}
B. Trend Analysis
// Store historical metrics
class CWVHistory {
constructor() {
this.history = JSON.parse(
localStorage.getItem('cwx-history') || '{}'
);
}
addMetric(storyId, metrics) {
if (!this.history[storyId]) {
this.history[storyId] = [];
}
this.history[storyId].push({
...metrics,
timestamp: Date.now()
});
// Keep last 30 entries
if (this.history[storyId].length > 30) {
this.history[storyId] = this.history[storyId].slice(-30);
}
localStorage.setItem('cwx-history', JSON.stringify(this.history));
}
getTrend(storyId, metric, days = 7) {
const entries = this.history[storyId] || [];
const cutoff = Date.now() - (days * 24 * 60 * 60 * 1000);
const recent = entries.filter(e => e.timestamp > cutoff);
if (recent.length < 2) return null;
const first = recent[0].metrics[metric];
const last = recent[recent.length - 1].metrics[metric];
const change = ((last - first) / first) * 100;
return {
change: change.toFixed(1),
direction: change > 5 ? 'degraded' : change < -5 ? 'improved' : 'stable'
};
}
}
C. Slack/Teams Notification
// In CI script
async function sendNotification(results, webhookUrl) {
const message = {
text: `CWV Check ${results.failed.length > 0 ? '❌ Failed' : '✅ Passed'}`,
attachments: [
{
color: results.failed.length > 0 ? 'danger' : 'good',
fields: [
{ title: 'Passed', value: results.passed.length.toString(), short: true },
{ title: 'Failed', value: results.failed.length.toString(), short: true },
{ title: 'Warnings', value: results.warnings.length.toString(), short: true }
]
}
]
};
await fetch(webhookUrl, {
method: 'POST',
body: JSON.stringify(message)
});
}
7. Best Practices & Recommendations
-
Start with warnings only: Don't block merges immediately. Use warnings for 2-3 sprints to allow teams to adapt.
-
Component-level granularity: Only check critical/user-facing components.
-
Baseline establishment:
# Generate baseline metrics
npx cwx-baseline
-
Exclude development/test components in stories-to-check.json:
{
"excludePatterns": [
"**/*test*",
"**/*spec*",
"**/__tests__/**",
"**/deprecated/**",
"**/wip/**"
]
}
-
Performance budgets:
- LCP: < 2.5s (good), < 4s (needs improvement)
- CLS: < 0.1 (good), < 0.25 (needs improvement)
- FID: < 100ms (good), < 300ms (needs improvement)
-
Run in parallel for faster CI:
// In cwx-gate.js
const batchSize = 5;
for (let i = 0; i < stories.length; i += batchSize) {
const batch = stories.slice(i, i + batchSize);
await Promise.all(batch.map(checkStory));
}
8. Docker Support (Optional)
Dfile:
FROM node:18-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 6006
CMD ["npx", "storybook", "dev", "--ci", "--host", "0.0.0.0", "--port", "6006"]
Key Considerations:
- Measurement environment: Uses iframe mode for isolated component measurement
- Performance overhead: Minimal (~100ms per story)
- False positives: Configure thresholds appropriately for your app complexity
- Caching: Metrics cached in localStorage for dev experience
- Mobile vs Desktop: Consider separate thresholds for different viewports
- A/B testing: Can integrate with feature flags for gradual rollouts
This system provides:
- ✅ Real-time feedback in Storybook
- ✅ CI/CD gatekeeping
- ✅ Historical trend tracking
- ✅ Configurable thresholds
- ✅ Team notifications
- ✅ Component-level granularity
The guardrail will fail PRs when:
- Any critical component exceeds thresholds
- (Optional) Non-critical components show warnings
- Metrics collection fails completely
Teams can then:
- Review failing stories in Storybook (with visual CWV panel)
- Optimize components before merge
- Request exemptions with justification for intentional trade-offs