We are going to build a system for enforcing browser performance budgets in a CI/CD pipeline.
The system will have three main components:
CI Checks: Automated performance tests that run on every commit/PR.
Budgets: Defined thresholds for key performance metrics (e.g., LCP, FID, CLS, etc.).
Alerts: Notifications when budgets are exceeded.
Steps:
Define the performance metrics and their budgets.
We'll use the Core Web Vitals as a baseline but can extend to other metrics.
Example budgets:
LCP (Largest Contentful Paint) <= 2.5s
FID (First Input Delay) <= 100ms
CLS (Cumulative Layout Shift) <= 0.1
Set up a way to measure these metrics in the CI environment.
We can use tools like:
Lighthouse (via lighthouse npm package or lighthouse-ci)
WebPageTest (via API)
Puppeteer with custom scripts to collect metrics
Since we are in CI, we might want to run against a built version of the site (static files) or a staging server.
Integrate the measurement into the CI pipeline (e.g., GitHub Actions, GitLab CI, Jenkins).
Example: In a GitHub Action, we run a script that:
a. Builds the project (if necessary)
b. Starts a local server (or uses a staging URL)
c. Runs the performance measurement tool
d. Compares the results against the budgets
Define the enforcement: if any metric exceeds the budget, the CI check fails.
Set up alerts (optional but recommended) for when the budgets are exceeded in CI.
This could be done via:
CI status (failed check)
Notifications to Slack/Email (via CI integration)
Consider also monitoring in production (using real user monitoring - RUM) and alerting when budgets are exceeded in the wild.
Implementation Plan:
We'll create a Node.js script that:
Takes a URL (or builds and serves locally) and runs Lighthouse (or another tool) to get the metrics.
Compares the metrics to the defined budgets.
Exits with a non-zero code if any budget is exceeded (so CI fails).
Alternatively, we can use lighthouse-ci which is designed for CI and can compare against budgets.
However, note that lighthouse-ci might not support all the metrics we want (like FID and CLS in the same way) and might require a specific setup.
Let's consider using lighthouse directly with a custom script for more control.
Steps in the script:
Parse command line arguments for:
URL (or maybe we build and get the local server URL)
Path to a budget configuration file (JSON)
Run Lighthouse for the given URL (with appropriate flags for the metrics we care about).
Extract the metrics from the Lighthouse report.
Compare against the budgets.
Output a report (maybe in the console and also as a JSON file for artifact).
Exit with code 0 if all good, 1 if any budget exceeded.
Example budget configuration (budgets.json):
{
"lcp": 2500,
"fid": 100,
"cls": 0.1
}
Note: Lighthouse reports LCP in ms, FID in ms, and CLS as a unitless number.
However, note that Lighthouse might not give FID in the same way as the field data. Also, note that CLS in Lighthouse is measured in a lab setting and might differ from field.
Alternatively, we can use the web-vitals library to measure these metrics in a real browser context (like in a Puppeteer script) but that might be more complex.
Since we are in CI and want a quick check, using Lighthouse is acceptable, but we should be aware of the limitations.
Another option is to use the lighthouse package and then use the metrics object from the report.
The metrics we are interested in are:
Largest Contentful Paint (LCP) -> metrics.LCP.median (or firstView and repeatView? We are only doing one run, so let's use firstView and take the median of the metrics? Actually, the lighthouse report returns an array of runs. We can take the median of the LCP values across runs? Or just take the first run? Lighthouse by default runs 3 times and gives an average? Actually, the metrics object in the report has firstView and repeatView for each metric. We are only interested in the first view (since it's a new visit). And within firstView, there is a median value.
But note: the lighthouse report structure:
report.json -> audits -> metrics -> ['first-view', 'repeat-view']? Actually, in the JSON output, the metrics are under audits.metrics.details.items[0] and then we have items for firstView and repeatView.
However, the lighthouse package returns a lhr (Lighthouse Result) object that has a getFirstViewFirstContentfulPaint() and similar methods, but for LCP we might need to look at lhr.audits['largest-contentful-paint'].displayValue? But that's the display string.
Alternatively, we can use the metrics audit:
lhr.audits.metrics.details.items[0].firstView.LCP
But note: the lhr object structure might change. We should look at the current structure.
Alternatively, we can use the lighthouse package's built-in getFirstViewFirstContentfulPaint and similar for LCP? Actually, I don't see a direct method for LCP.
But note: we might want to run multiple times and take the median? The lighthouse package by default runs 3 times and returns an array of results? Actually, the runnerResult has lhr which is the aggregated result? Wait, the lighthouse function returns an array of runs? Actually, the documentation says:
lighthouse(url, options, config, runner)
It returns a promise that resolves to an array of Lighthouse Results (each run). But by default, it runs 3 times? Actually, the default numRuns is 3.
So we get an array of 3 LHR objects. We can then take the median of each metric? Or we can let Lighthouse aggregate? Actually, the lhr object we get from each run is for that run. We can aggregate ourselves.
Alternatively, we can set options to have onlyCategories and output and then we get 3 runs. Then we can extract the metrics from each run and take the median.
But note: the lighthouse package also has a Lighthouse class that can be configured to run multiple times and then aggregate? Actually, the default is to run 3 times and then the runnerResult has lhr which is the first run? I think the lighthouse function returns an array of results for each run.
But note: the numericValue might be 0 if the audit failed? We should check for that.
Alternatively, we can use the lhr.audits['largest-contentful-paint'].score? But that's a score between 0 and 1.
We want the raw value in ms.
Let's assume we take the median of the numericValue.
Implementation of median:
function median(values) {
if (values.length === 0) return 0;
values.sort((a, b) => a - b);
const mid = Math.floor(values.length / 2);
return values.length % 2 === 0 ? (values[mid-1] + values[mid]) / 2 : values[mid];
}
However, note that if any run fails to get the metric, we might get undefined? We should filter out non-numeric values? Or treat as 0? Actually, if the audit is not applicable, it might be null? We should check the audit's numericValue property.
Alternatively, we can use the lhr.audits['largest-contentful-paint'].displayValue but that's a string.
So we stick to numericValue.
But note: the numericValue for LCP is in milliseconds.
Similarly for CLS and FID.
However, note that the CLS audit might not be present in older versions? We are using a recent version.
Let's code accordingly.
Steps:
Read the budget config from a file.
Run Lighthouse 3 times (by default) for the given URL.
For each metric (lcp, fid, cls) we care about, collect the numericValue from each run.
Compute the median for each metric.
Compare the median with the budget.
If any median exceeds the budget, exit with code 1 and print which ones.
But note: what if we want to use the 75th percentile? The Core Web Vitals use the 75th percentile. However, in CI we are running synthetic tests and might not have enough samples. We are only running 3 times. Maybe we take the worst? Or the median? The median of 3 is the second value when sorted.
Alternatively, we can set options to run more times? But that would take longer.
Let's stick to the median of 3 runs.
However, note that the lighthouse package might aggregate by itself? Actually, the lhr we get from each run is individual. We are doing our own aggregation.
But wait, the lighthouse package when run with numRuns > 1, the runnerResult has an array of lhr for each run.
We can change the options to set numRuns to 3 (default) or more.
- Parse arguments.
- Read budgets file.
- Run lighthouse with the given URL and options (output: 'json', onlyCategories: ['performance']).
- Wait for the runs.
- For each metric in the budgets, collect the numericValue from each run's audit.
- Compute the median.
- Compare.
However, note that the audit names in Lighthouse might be:
- 'largest-contentful-paint'
- 'first-input-delay'
- 'cumulative-layout-shift'
But we can also use the lhr.audits keys.
We'll map our budget metric names to audit names.
Alternatively, we can use the lhr.metrics? Actually, the lhr has a metrics property that is an object with the metric names (like 'LCP') and their values? Let me check:
But note: the firstView might have other metrics, but we only care about these three.
However, the lhr.audits.metrics might not be present in older versions? We are using a recent version.
Let's assume we use lighthouse version 9 or above.
Alternatively, we can use the individual audits as fallback.
But let's stick to the metrics audit.
Code:
const lcpValues = [];
const fidValues = [];
const clsValues = [];
for (const lhr of lhrs) {
const metricsAudit = lhr.audits.metrics;
if (!metricsAudit) {
console.error('Metrics audit not found in Lighthouse run');
process.exit(1);
}
const firstView = metricsAudit.details.items[0].firstView;
lcpValues.push(firstView.LCP);
fidValues.push(firstView.FID);
clsValues.push(firstView.CLS);
}
Then compute the median for each.
But note: what if the run fails and we get undefined? We should check and maybe skip? But then we don't have enough samples? We can throw an error.
Alternatively, we can set the value to 0 if undefined? But that might be misleading.
Let's assume that if any run fails to get the metric, we consider the whole check as failed? That's safe.
So:
if (lcpValues.length !== lhrs.length) { ... error }
Actually, we are pushing for every run, so if the property is undefined, we push undefined. Then when we compute median, we might get NaN? We should check.
Let's do:
for (const lhr of lhrs) {
const metricsAudit = lhr.audits.metrics;
if (!metricsAudit) {
throw new Error('Metrics audit not found');
}
const firstView = metricsAudit.details.items[0].firstView;
if (firstView.LCP === undefined) {
throw new Error('LCP not found in metrics');
}
// same for others
lcpValues.push(firstView.LCP);
fidValues.push(firstView.FID);
clsValues.push(firstView.CLS);
}
But note: the CLS unit is the same (no unit) and FID in ms.
We are comparing numbers.
Now, we need to consider that the lighthouse package might not be installed in the CI environment. We'll have to install it as a dev dependency.
Alternatively, we can use lighthouse-ci which is designed for CI and has built-in budget comparison. But we want to have custom aggregation (median) and maybe more control.
However, lighthouse-ci might be easier. Let's consider:
But the --assert option in lighthouse-ci uses the assert feature of Lighthouse, which is different? Actually, the lighthouse-ci tool has its own budget format and can run multiple URLs and aggregate.
But note: the lighthouse-ci by default runs 3 times and then uses the median? I think it uses the 75th percentile by default? Actually, the lighthouse-ci uses the Lighthouse assert feature which by default uses the median? I'm not sure.
Alternatively, we can use lighthouse with our own script as above.
Given the complexity and the need for custom aggregation, I think writing our own script is acceptable.
However, note that lighthouse requires Chrome to be installed. In CI, we might need to install Chrome or use a Docker image with Chrome.
We can use the chrome-launcher which will try to find an installed Chrome.
In CI, we can use a service like puppeteer which comes with Chromium, but that might be heavy.
Alternatively, we can use the lighthouse Docker image? But that's for running the Lighthouse server.
We'll assume that the CI environment has Chrome installed.
Steps for CI:
- Install Node.js and dependencies (including lighthouse and chrome-launcher).
- Run the script.
But note: the chrome-launcher might not work in some CI environments because of sandboxing. We might need to pass --no-sandbox flag.
We'll also want to output a JSON file with the results and the medians for artifact.
Let's code:
#!/usr/bin/env node
const fs = require('fs');
const lighthouse = require('lighthouse');
const chromeLauncher = require('chrome-launcher');
function median(values) {
if (values.length === 0) return 0;
values.sort((a, b) => a - b);
const mid = Math.floor(values.length / 2);
return values.length % 2 === 0 ? (values[mid-1] + values[mid]) / 2 : values[mid];
}
async function runLighthouse(url) {
const chrome = await chromeLauncher.launch({chromeFlags: ['--headless', '--no-sandbox']});
try {
const options = {
logLevel: 'info',
output: 'json',
onlyCategories: ['performance'],
// We can set more options if needed, like port, etc.
};
const runnerResults = await lighthouse(url, options, chrome);
return runnerResults.map(r => r.lhr);
} finally {
await chrome.kill();
}
}
async function main() {
// Parse arguments
const args = process.argv.slice(2);
let url, budgetsPath;
for (let i = 0; i < args.length; i++) {
if (args[i] === '--url' && i+1 < args.length) {
url = args[i+1];
i++;
} else if (args[i] === '--budgets' && i+1 < args.length) {
budgetsPath = args[i+1];
i++;
}
}
if (!url || !budgetsPath) {
console.error('Usage: node perf-budget.js --url <url> --budgets <budgets.json>');
process.exit(1);
}
const budgetsConfig = JSON.parse(fs.readFileSync(budgetsPath, 'utf8'));
const budgets = budgetsConfig.metrics;
const lhrs = await runLighthouse(url);
const lcpValues = [];
const fidValues = [];
const clsValues = [];
for (const lhr of lhrs) {
const metricsAudit = lhr.audits.metrics;
if (!metricsAudit) {
throw new Error('Metrics audit not found in Lighthouse run');
}
const firstView = metricsAudit.details.items[0].firstView;
if (firstView.LCP === undefined) {
throw new Error('LCP not found in metrics');
}
if (firstView.FID === undefined) {
throw new Error('FID not found in metrics');
}
if (firstView.CLS === undefined) {
throw new Error('CLS not found in metrics');
}
lcpValues.push(firstView.LCP);
fidValues.push(firstView.FID);
clsValues.push(firstView.CLS);
}
const medianLCP = median(lcpValues);
const medianFID = median(fidValues);
const medianCLS = median(clsValues);
const results = {
url,
lcp: medianLCP,
fid: medianFID,
cls: medianCLS,
budgets,
passed: true
};
if (medianLCP > budgets.lcp) {
console.error(`LCP budget exceeded: ${medianLCP}ms > ${budgets.lcp}ms`);
results.passed = false;
}
if (medianFID > budgets.fid) {
console.error(`FID budget exceeded: ${medianFID}ms > ${budgets.fid}ms`);
results.passed = false;
}
if (medianCLS > budgets.cls) {
console.error(`CLS budget exceeded: ${medianCLS} > ${budgets.cls}`);
results.passed = false;
}
// Write results to a file for artifact
fs.writeFileSync('perf-budget-results.json', JSON.stringify(results, null, 2));
if (!results.passed) {
process.exit(1);
}
}
main().catch(err => {
console.error(err);
process.exit(1);
});
But note: the firstView might have the metrics in a different structure? Actually, the metrics audit returns an object with firstView and repeatView and each has the metrics as properties.
However, the property names are 'LCP', 'FID', 'CLS' (uppercase). We used uppercase? In the code above we used firstView.LCP, etc.
But note: the lhr.audits.metrics.details.items[0] is the first (and only) item in the array? Actually, the metrics audit returns an array of Metric objects? Wait, the structure of the metrics audit:
In CI, we can run this after deploying to staging.
Now, for the CI integration (example for GitHub Actions):
name: Performance Budget
on:
pull_request:
branches: [ main ]
jobs:
perf-budget:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Setup Node
uses: actions/setup-node@v2
with:
node-version: '16'
- name: Install dependencies
run: npm ci
- name: Build and deploy to staging (if needed)
run: |
npm run build
# We assume we have a way to deploy to staging, maybe using a service or just start a local server?
# For example, we can use `serve` to serve the build folder.
npx serve -s build -l 3000 &
SERVER_PID=$!
# Wait for server to be ready
npx wait-on http://localhost:3000
# Run the perf budget script against localhost:3000
node perf-budget.js --url http://localhost:3000 --budgets budgets.json
kill $SERVER_PID
But note: the wait-on package might be needed. We can install it as a dev dependency.
Alternatively, we can use a staging URL that is already deployed.
We'll leave the CI integration details to the user.
Now, what about alerts? The CI check failing is already an alert. But we can also send a Slack notification when the check fails.
We can use the actions/slack action in GitHub Actions to send a message when the job fails.
But that's outside the scope of the script.
Alternatively, we can have the script send a Slack message if the budget is exceeded? That might be too heavy for the script.
We'll leave the alerting to the CI system.
However, we can also consider running this in production with RUM data? That's a different story.
This script is for synthetic testing in CI.
Let's improve:
We might want to allow the user to specify the number of runs? We can add a --runs option.
We might want to allow different aggregation methods (median, 75th percentile, worst)? We can add a --aggregate option.
But for simplicity, we'll stick to median.
Now, let's consider that the lighthouse package might have changed and the metrics audit might not be present? We can fallback to individual audits.
We can write a helper function to get the metric from an audit by name:
function getMetricFromAudit(lhr, auditName) {
const audit = lhr.audits[auditName];
if (!audit) {
throw new Error(`Audit ${auditName} not found`);
}
return audit.numericValue;
}
But note: the lighthouse package might require a specific version. We'll specify in package.json:
"devDependencies": {
"lighthouse": "^9.0.0"
}
We'll also need chrome-launcher.
Now, we must consider that the lighthouse package might have breaking changes. We'll lock the version.
This script is a starting point.
For production use, we might want to:
- Add more metrics (like TTI, TBT, etc.)
- Allow more budget types (like for each metric, we can have multiple thresholds: error, warning)
- Output in different formats (e.g., HTML, JSON, console)
But for the purpose of a CI check, this should be enough.
Let's also note that the lighthouse package might require a lot of memory and time. In CI, we might want to run in parallel? We are only running against one URL.
If we have multiple pages, we can extend the script to take multiple URLs and then take the worst? Or average? That's up to the configuration.
We'll keep it simple for one URL.
Now, let's write the script with error handling and logging.
We'll also add a timeout for Lighthouse? The lighthouse function has a timeout option? Actually, the options passed to lighthouse can have timeout? I think the lighthouse package uses a default timeout of 45 seconds? We can set it.
But note: the lighthouse package might not accept numRuns in the options? Actually, the options for lighthouse are the same as the flags in the CLI? I think numRuns is a valid option.
The options are the same as the CLI flags? Actually, the options are the same as the flags in the CLI? The numRuns is a flag.
So we can set numRuns in options.
Now, we are done.
However, note that the lighthouse package might change the structure of the report. We should be cautious.
We can also use the lhr object's getFirstViewFirstContentfulPaint and similar? But for LCP, there is no such method.
Alternatively, we can use the lhr.audits and look for the audit with id 'largest-contentful-paint'. That might be safer because the audit id is stable.
Let's change the getMetricsFromLHR to use the audit id:
This is simpler and doesn't depend on the metrics audit structure.
But note: the numericValue might be 0 if the audit didn't run? We are okay with that.
Let's use this.
Final script with this change.
Now, we have a script that:
- Runs Lighthouse multiple times.
- Extracts the metrics from individual audits (more stable).
- Computes the median.
- Compares with budgets.
We'll output a JSON file with the results.
Now, let's consider that we might want to run against multiple URLs? We can extend the script to take an array of URLs and then take the worst metric? But that's up to the user.
We'll keep it simple.
Now, for the CI checks, we can run this script for the main pages (home, product, etc.) and fail if any of them exceed the budget.
We can create a separate budget file for each page? Or have an array of URLs in the config?
We can change the script to accept a JSON config with multiple URLs and budgets per URL? Or we can run the script multiple times.
We'll leave it as one URL per run for simplicity.
The user can set up a matrix in CI to run against multiple URLs.
Create a budgets.json file with the metrics and their thresholds.
Install the dependencies: npm install lighthouse chrome-launcher
Run the script: node perf-budget.js --url <url> --budgets budgets.json
We can also publish this as an npm package.
But for now, we'll just have the script.
We'll also note that the lighthouse package requires Chrome to be installed. In CI, we can use the puppeteer package to download Chromium? But that would be heavy.
Alternatively, we can use the chrome-aws-lambda package if we are in AWS Lambda? But we are in CI.
We'll assume Chrome is installed in the CI environment.
For GitHub Actions, we can use the actions/setup-chrome action? Actually, there is an action to setup Chrome.
But we can also use the ubuntu-latest which comes with Chrome? I think it does.
We'll leave that to the user.
Now, let's write the script with the fallback to individual audits.
Now, note that the lighthouse package might be heavy and slow. We might want to run it only on PRs to main, not on every commit.
We can set up the CI to run on pull requests only.
Also, we might want to cache the node_modules to speed up.
But that's CI configuration.
This script is a standalone tool that can be integrated into any CI.
We can also extend it to support more metrics by adding them to the getMetricsFromLHR and the budgets.
But for now, we have the three Core Web Vitals.
Let's consider that the numericValue for CLS might be a very small number? We are comparing as numbers.
Now, we have a working solution.
However, note that the lighthouse package might have a bug where the numericValue for FID is 0 even when there is an input? We should test.
We can run against a page that has a button and click it? But in synthetic tests, we don't interact. So FID might be 0 if there is no input during the run? That's acceptable because the budget is for the worst-case scenario? Actually, the FID metric is about the worst input delay. In Lighthouse, they simulate an input? I think they do.
But if the page has no interactive elements, then FID will be 0? Then we might pass even if the page is not interactive? That's a problem.
Actually, the FID audit in Lighthouse requires that there is an interactive element? I think it will simulate a click on the first interactive element? If there is none, then the audit might not run? Then we get undefined? We throw an error.
So we are safe.
But if the page has an interactive element, then we get a value.
We can now set up the CI to run this and fail the build if the budget is exceeded.
For the alerts, we can rely on the CI's notification (like GitHub's failed check) or set up a Slack notification for failed jobs.
This is a solid foundation.
We can also consider:
- Using the `lighthouse` CI tool (https://github.com/GoogleChrome/lighthouse-ci) which has more features like running against a list of URLs and generating reports.
But for a simple budget enforcement, our script is enough.
Let me know if you have any questions.
I'll help you build a comprehensive browser performance budget enforcement system. This will include CI/CD integration, configurable budgets, and alerting mechanisms.