Performance Data Reporting

Collect performance metrics with the Performance API and web-vitals, and report them to your server.

🎯 Introduction

Event tracking tells us what users do, but not whether the page is fast. Instant loading on your development machine says little about an older phone on a slow network. Performance reporting collects metrics from real users' devices and sends them to a server for aggregation. This approach is called RUM (Real User Monitoring).

By the end of this article, you will be able to:

  • Read navigation durations and paint timestamps using the browser's Performance API.
  • Collect the three Core Web Vitals—LCP, INP, and CLS—with web-vitals.
  • Send metrics with sendBeacon to complete the collection → reporting flow.

🧱 Collecting Metrics with the Performance API

The browser's Performance API records timing information for stages of page loading. Read entries by type with performance.getEntriesByType(type). A common type is navigation:

timing.js
// Read after the page loads so the timing data is complete
window.addEventListener('load', () => {
    const [nav] = performance.getEntriesByType('navigation');

    console.log('Server response time', Math.round(nav.responseStart - nav.requestStart));
    console.log('Time to DOMContentLoaded completion', Math.round(nav.domContentLoadedEventEnd));
    console.log('Time to full page load', Math.round(nav.loadEventEnd));
});

Fields on nav are timestamps in milliseconds for loading milestones. Subtract two to get a stage's duration: responseStart - requestStart measures server response time, while loadEventEnd represents total time until loading completes.

Another useful entry type is paint:

timing.js
performance.getEntriesByType('paint').forEach((entry) => {
    console.log(entry.name, Math.round(entry.startTime));
    // first-paint: the first pixels rendered on screen
    // first-contentful-paint: the first text, images, or other content rendered
});

startTime is the number of milliseconds since navigation began and can be used directly. first-contentful-paint (FCP) marks the point when the user first sees content instead of a blank page.

Read navigation entries after the load event. Reading too early leaves fields such as loadEventEnd at 0, producing incorrect zero or negative durations.
For now, remember that navigation describes loading stages and paint indicates when content first appears. Look up other fields in MDN as you need them.

🧱 The web-vitals Library

Accurately measuring LCP, INP, and CLS manually is difficult: LCP updates as content renders, INP tracks interactions across the visit, and CLS accumulates layout shifts. Google's web-vitals library encapsulates this in three functions. See Performance Metrics and Lighthouse in the Performance Optimization course for definitions and thresholds; here we focus on collection and reporting.

Install the library first. These examples were verified with Node.js v22 and web-vitals v5.x:

pnpm add web-vitals

Each function corresponds to one metric; metric.value in its callback contains the value:

vitals.js
import { onLCP, onINP, onCLS } from 'web-vitals';

onLCP((metric) => console.log('LCP (ms)', Math.round(metric.value)));
onINP((metric) => console.log('INP (ms)', Math.round(metric.value)));
onCLS((metric) => console.log('CLS (unitless score)', metric.value.toFixed(2)));
These callbacks do not simply run as soon as the page loads. For metrics that keep updating, such as LCP, the library waits until the page is hidden or closed to report a final value. During local testing, switch to another tab and back to see console output. This is expected behavior.

🧱 Reporting to the Server

Use sendBeacon from the previous article to let the browser send data even as the page closes. This suits metrics whose final values are available only at the end of a visit. Here is a complete minimal collection and reporting example:

vitals.js
import { onLCP, onINP, onCLS } from 'web-vitals';

function report(metric) {
    const data = {
        name: metric.name, // Metric name: LCP / INP / CLS
        value: Math.round(metric.value), // Round before reporting
        path: location.pathname, // Page being measured
    };

    const body = JSON.stringify(data);
    navigator.sendBeacon('/api/monitor/performance', new Blob([body], { type: 'application/json' }));
}

onLCP(report);
onINP(report);
onCLS(report);

path identifies the page. Performance can vary substantially between pages, so aggregate each separately; combining them obscures useful findings. The server can store the JSON and aggregate by page and time. Storage and dashboards belong to the backend; the frontend's job is to measure accurately and send the data.

You can send FCP and server response time from the Performance API through the same report function, as long as the field structure stays consistent.

❓ Questions and Answers

Q1: Why is there no console output after loading when I registered onLCP?

This is expected. LCP updates as content renders, and the library reports the final value when the page is hidden or closed. Switch tabs during local testing to trigger it.

Q2: Why use sendBeacon rather than fetch?

Performance metrics often become available as the page closes, when the browser may cancel an ongoing fetch and lose the data. With sendBeacon, the browser takes over delivery. See Event Tracking and Data Reporting for the comparison.

Q3: Is reporting every user's every visit too much data?

Use sampling, for example Math.random() < 0.1 to report for roughly one in ten users. The sample can still reflect overall performance; adjust the rate to your traffic.


🧪 Exercises

Exercise 1: Use the Performance API to calculate server response time, from sending the request to receiving the first byte, then round and print it:

window.addEventListener('load', () => {
    const [nav] = performance.getEntriesByType('navigation');

    // Write your code here: calculate and print server response time
});

Exercise 2: Add a ua field with the value navigator.userAgent to the reported data so the server can group results by browser:

function report(metric) {
    const data = {
        name: metric.name,
        value: Math.round(metric.value),
        path: location.pathname,
        // Write your code here: add the ua field
    };

    const body = JSON.stringify(data);
    navigator.sendBeacon('/api/monitor/performance', new Blob([body], { type: 'application/json' }));
}

Afterward, consider whether there is a simpler way to distinguish mobile and desktop visits than sending the full user agent string.


🎉 You now know how to report performance data! Next, we will use Sentry to set up error and performance monitoring with just a few configuration options.