Core Web Vitals · Performance · JavaScript · Monitoring
Measuring Core Web Vitals from Real Users with the web-vitals Library
Collect LCP, INP and CLS from real visitors with the web-vitals library: attribution data, batching with sendBeacon, a small collection endpoint and p75 reporting per page type.

On the health-tourism and corporate sites I build, Lighthouse scores are easy to get green: it measures a fast machine on a simulated network, once. Search Console's Core Web Vitals report, on the other hand, reflects real phones on real connections, and it updates slowly. The gap between the two is where surprises live, especially for INP, which a lab run can't measure at all. So every site I ship now gets a small real user monitoring (RUM) setup alongside lab tests. It costs a few kilobytes and answers the question lab tools can't: what are users actually experiencing?
Lab data vs field data
| Lab (Lighthouse, CI) | Field (RUM, CrUX) | |
|---|---|---|
| Device and network | Fixed profile | Whatever users have |
| INP | Not measured (no real interactions) | Measured |
| Good for | Catching regressions before merge | Knowing real experience, prioritising |
| Delay | Immediate | Hours for your own RUM, 28 days for CrUX |
You need both. The lab side is covered in performance budgets with Lighthouse CI; this post is the field side.
Collecting the metrics
Google's web-vitals library handles the hard edge cases: back/forward cache restores, pages opened in background tabs, CLS session windows and INP's choice of interaction. Use the attribution build so each report tells you why a value is bad, not only that it is.
import { onCLS, onINP, onLCP, onTTFB, type MetricWithAttribution } from 'web-vitals/attribution';
const queue: Record<string, unknown>[] = [];
function enqueue(metric: MetricWithAttribution) {
const base = {
name: metric.name,
value: Math.round(metric.name === 'CLS' ? metric.value * 1000 : metric.value),
rating: metric.rating,
id: metric.id,
nav: metric.navigationType,
page: document.body.dataset.pageType ?? 'other',
conn: (navigator as any).connection?.effectiveType ?? 'unknown',
};
queue.push({ ...base, ...describe(metric) });
}
onLCP(enqueue);
onINP(enqueue);
onCLS(enqueue);
onTTFB(enqueue);
Two details matter. First, report a page type (home, blog post, service page) instead of the full URL; percentiles per template are actionable, percentiles per URL are noise on a small site. Second, CLS is a small decimal, so I multiply it by 1000 to store integers.
Attribution: the part that makes it useful
A poor INP value alone sends you hunting. The attribution build breaks it into phases and tells you which element was involved:
function describe(metric: MetricWithAttribution) {
switch (metric.name) {
case 'INP': {
const a = metric.attribution;
return {
target: a.interactionTarget,
type: a.interactionType,
inputDelay: Math.round(a.inputDelay),
processing: Math.round(a.processingDuration),
presentation: Math.round(a.presentationDelay),
};
}
case 'LCP': {
const a = metric.attribution;
return {
ttfb: Math.round(a.timeToFirstByte),
loadDelay: Math.round(a.resourceLoadDelay),
loadTime: Math.round(a.resourceLoadDuration),
renderDelay: Math.round(a.elementRenderDelay),
};
}
case 'CLS':
return { target: metric.attribution.largestShiftTarget };
default:
return {};
}
}
How to read it:
- INP with high input delay: the main thread was busy when the user clicked, often a third-party script or hydration. High processing time means your event handler is slow. High presentation delay means the DOM update after the handler is expensive.
- LCP with high load delay: the browser found the hero image late; preload it or put it in the HTML. High render delay with a fast load usually means render-blocking CSS or fonts.
- CLS with a target: the selector of the element that moved most, which usually points straight at an image without dimensions or a late-loading banner.
The fixes themselves are in Core Web Vitals for a heavy React app.
Sending without hurting the page
Don't send a request per metric. Batch them and flush when the page is hidden, which is the last reliable moment on mobile:
function flush() {
if (!queue.length) return;
const body = JSON.stringify(queue.splice(0));
if (!navigator.sendBeacon('/api/vitals', body)) {
fetch('/api/vitals', { method: 'POST', body, keepalive: true });
}
}
addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') flush();
});
visibilitychange is more reliable than unload or beforeunload, which often don't fire on mobile and can block the back/forward cache. Load the whole module lazily after the page is interactive so measuring doesn't affect what you measure.
A tiny collection endpoint
You don't need a product for this. A Worker or small Node.js endpoint that validates and stores rows is enough:
app.post('/api/vitals', express.text({ type: '*/*', limit: '16kb' }), async (req, res) => {
const rows = JSON.parse(req.body);
if (!Array.isArray(rows) || rows.length > 20) return res.status(400).end();
const allowed = new Set(['LCP', 'INP', 'CLS', 'TTFB']);
await db.insertVitals(
rows.filter((r) => allowed.has(r.name) && Number.isFinite(r.value))
.map((r) => ({ ...r, ua: req.get('user-agent'), at: new Date() })),
);
res.status(204).end();
});
Treat it like any public endpoint: size limits, validation and a rate limit. Note that sendBeacon sends text/plain, hence the express.text parser.
Reporting: p75, not averages
Google evaluates Core Web Vitals at the 75th percentile, so report the same way. An average hides the slow tail that the threshold is built around.
SELECT page, name,
percentile_cont(0.75) WITHIN GROUP (ORDER BY value) AS p75,
count(*) AS samples
FROM vitals
WHERE at > now() - interval '7 days'
GROUP BY page, name
HAVING count(*) > 50
ORDER BY page, name;
Then segment: mobile vs desktop, connection type, first visit vs back/forward navigation. Browser support for LCP and INP differs between engines and versions, so also split by browser before comparing numbers across them.
Privacy
Collect only what you need. A page type instead of a full URL, no query strings, no user IDs. Element selectors from attribution can contain user-generated IDs on some apps; truncate or hash them if so.
Conclusion
Lab tests stop regressions; field data tells you what to fix first. With web-vitals/attribution, a batched beacon on visibilitychange, a small validated endpoint and p75 reports per page type, you get a RUM setup you fully own in an afternoon. Start with INP: it is the metric lab tools can't show you, and the attribution phases usually point at the fix directly.


