Create CWV gates: budgets, regression checks, and rollbacks.
- User
Create CWV gates: budgets, regression checks, and rollbacks.
Assistant
Create CWV gates: budgets, regression checks, and rollbacks.
1. Understand the Goal: The user wants to create Core Web Vitals (CWV) "gates". In the context of web development and CI/CD (Continuous Integration/Continuous Deployment), "gates" are automated checks that prevent code from being deployed or merged if certain criteria aren't met. The specific gates requested are: * Budgets: Setting thresholds for performance metrics (LCP, INP, CLS). * Regression Checks: Comparing current performance against a baseline (previous build). * Rollbacks: Automatically reverting a deployment if metrics degrade in production.
Identify the Key Technologies:
@lhci/cli (Lighthouse CI) is the most robust tool for this specific workflow.Structure the Solution: I need to provide a practical, actionable guide. A good structure would be:
lighthouserc.json).Drafting Content - Part 1: Budgets (The Assertion Config):
assertions block in config.largest-contentful-paint, cumulative-layout-shift, total-blocking-time (or interaction-to-next-paint if supported, though Lighthouse sometimes uses TBT as a proxy, newer versions support INP). Let's stick to standard Lighthouse audit IDs.error (block the build) vs warn.Drafting Content - Part 2: Regression Checks:
assert command against a uploaded base branch result.main.lighthouserc.json, this is done via the assertions logic. You can set aggregationMethod and numeric limits.assert with specific numeric checks for budgets, and explain that Lighthouse CI automatically compares against previous runs if you set up the server, but for a simple gate, we often look for differences.assert with minScore or percentage changes is usually complex in standard LHCI without a server.lighthouserc assertions.compare or by asserting that a metric is within X% of the median.lighthouserc, you can assert specific metrics.Drafting Content - Part 3: The CI Pipeline (GitHub Actions):
lhci autorun.Drafting Content - Part 4: Rollbacks:
vercel rollback).Refining the Code Examples:
Config (lighthouserc.json):
ci.collect.ci.assert.error level.Regression Logic:
largest-contentful-paint: { maxNumericValue: 2500 } is a Budget.speed-index: { minScore: 0.9 }.budgets.json or assertions. The easiest way to explain "regression" in LHCI is relying on the assert command to check against the project baseline if using LHCI Server, or just setting strict budgets.assert block to handle hard limits (Budgets) and use aggregationMethod: 'median-run' to ensure we aren't just hitting a flaky run.Rollback Logic:
curl based example or a script that triggers a webhook.Review against constraints:
maxNumericValue.Final Polish:
largest-contentful-paint, cumulative-layout-shift, total-blocking-time (as proxy for INP usually in Lighthouse, but standard is INP now). Note: Lighthouse audit ID for INP is experimental-interaction-to-next-paint in some versions, but generally standard is total-blocking-time for lab data. I should mention TBT and INP. Self-correction: Lighthouse 10+ supports INP.Constructing the Output:
lighthouserc.json. This covers Budgets.(Self-Correction during drafting Step 2): How do I implement "Regression" specifically?
LHCI has a --failOnComparisonFailure flag (not exactly). The lhci autorun command runs assert.
To check regressions vs base branch:
assert feature to check if the current run violates the budget. This is effectively the budget gate.
To explicitly check for "Regression" (e.g., +100ms), you define a budget that is dynamically calculated or use a tool like web-vitals library in a Playwright script.
Decision: Stick to the industry standard LHCI. It's the most robust way to do budgets. For "Regression", I will explain how to compare PR against Main using LHCI's built-in temporary storage or Github Status checks.Let's refine the "Rollback" part. It's risky to automate rollbacks purely on synthetic data (flakiness). I should add a warning.
Final Plan:
lighthouserc.json with strict assertions (LCP, CLS, INP/TBT).main in GitHub Actions.Let's write it. To implement Core Web Vitals (CWV) gates effectively, you need a layered approach: Static Analysis (Budgets), Pre-deployment Verification (Regression), and Post-deployment Safety (Rollbacks).
The industry standard for this workflow is Lighthouse CI (LHCI) combined with your CI/CD provider (like GitHub Actions).
Here is a complete implementation guide.
First, define your strict budgets and assertion logic. This file tells Lighthouse to fail the build if specific metrics cross a threshold.
Create a file named lighthouserc.json in your project root:
{
"ci": {
"collect": {
"numberOfRuns": 3,
"settings": {
"preset": "desktop",
"onlyCategories": ["performance"]
}
},
"assert": {
"assertions": {
"categories:performance": ["error", {"minScore": 0.9}],
"first-contentful-paint": ["error", {"maxNumericValue": 1000}],
"largest-contentful-paint": ["error", {"maxNumericValue": 2000}],
"cumulative-layout-shift": ["error", {"maxNumericValue": 0.05}],
"total-blocking-time": ["error", {"maxNumericValue": 200}],
"resource-summary:script:size": ["warn", {"maxNumericValue": 512000}],
"resource-summary:total:size": ["error", {"maxNumericValue": 1572864}]
}
},
"upload": {
"target": "temporary-public-storage"
}
}
}
error: Blocks the build.warn: Alerts developers but allows the build.This pipeline runs on every Pull Request. It builds your app, starts it, and runs Lighthouse assertions against it. If the assertions fail, the PR cannot be merged.
File: .github/workflows/cwv-gate.yml
name: CWV Gates
on:
pull_request:
branches: [main]
jobs:
lighthouse-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'
- name: Install Dependencies
run: npm ci
- name: Build Application
run: npm run build
# Run Lighthouse CI
- name: Run Lighthouse CI
uses: treosh/lighthouse-ci-action@v11
with:
configPath: ./lighthouserc.json
uploadArtifacts: true
temporaryPublicStorage: true
How this works:
assert rules from step 1.A rollback is a reaction to Real User Monitoring (RUM) or a failed production health check. Since CWV data from real users (CrUX) takes 28 days to update, for instant rollbacks, we usually monitor "Synthetic Production Canaries" or Server-Side timing headers.
Below is a script that queries a production monitoring endpoint (like SpeedCurve, Calibre, or a custom health lambda). If performance degrades, it triggers a Platform API Rollback (e.g., Vercel).
File: scripts/production-watchdog.js
// This script would run on a schedule (e.g., every 10 mins) in your CI
const axios = require('axios');
const THRESHOLD_LCP = 2500; // 2.5s
const VERCEL_DEPLOYMENT_ID = process.env.VERCEL_DEPLOYMENT_ID;
const VERCEL_TOKEN = process.env.VERCEL_TOKEN;
async function checkPerformance() {
try {
// 1. Fetch CWV data from your Real User Monitoring provider or Synthetic API
// Example: Checking a custom Lambda that calculates LCP via Chrome UX Report API
const response = await axios.get('https://your-monitoring-api.com/metrics?domain=example.com');
const { lcp, cls } = response.data;
console.log(`Current Prod LCP: ${lcp}ms`);
// 2. Regression Logic
if (lcp > THRESHOLD_LCP) {
console.error(`🔴 REGRESSION DETECTED! LCP ${lcp}ms > Limit ${THRESHOLD_LCP}ms`);
await triggerRollback();
} else {
console.log('✅ CWV Budgets passing.');
}
} catch (error) {
console.error('Error fetching metrics', error);
}
}
async function triggerRollback() {
console.log('⏪ Initiating Rollback...');
// Example: Triggering a Vercel Rollback via API
// This finds the previous stable deployment and promotes it
await axios.post(
`https://api.vercel.com/v13/deployments/${VERCEL_DEPLOYMENT_ID}/events`,
{ type: 'rollback' },
{
headers: {
Authorization: `Bearer ${VERCEL_TOKEN}`,
'Content-Type': 'application/json'
}
}
);
// Alert the team via Slack/PagerDuty here
process.exit(1); // Fail the job to alert CI
}
checkPerformance();
lighthouserc.json.production-watchdog.js runs in production. If a deployment causes a spike in LCP/CLS (verified via API), it calls the hosting provider's API (Vercel/AWS/Netlify) to instantly revert to the previous stable commit.