Real user monitoring sends what each visit measured to your server. Sending each metric the moment it's ready costs a request apiece, and CLS and INP only settle when the reader leaves. Write createMetricQueue(url), which returns { add(metric) } and batches metrics as the web-vitals 6.2.3 README suggests: queue them, and send the queue when the page is hidden.
add(metric) queues a metric, an object with an id (and anything else, like name, value, and delta). If a metric with the same id is already waiting, the new one takes its place in the queue: web-vitals reports CLS and INP again, with the same id, when they change, and only the latest needs to go.
When a visibilitychange event finds document.visibilityState is "hidden", send everything waiting in one request and empty the queue. The body is JSON.stringify of the array of metrics, in the order they were first added. A later hide sends only what was added since, and an empty queue sends nothing. Listen on window without the capture phase: web-vitals reports CLS and INP from capture-phase listeners for the same event, and yours runs after those, so their last reports go out too.
Send with navigator.sendBeacon(url, body). It hands the data to the browser, which delivers it even if the page is closing, and it returns false when it won't take it (the browser allows 64 KiB of such data in flight). Where navigator.sendBeacon isn't a function, or it returns false, send fetch(url, { method: "POST", body, keepalive: true }) instead: keepalive lets that request outlive the page too.
const metrics = createMetricQueue("/analytics");
metrics.add({ name: "LCP", value: 1460, delta: 1460, id: "v6-1" });
metrics.add({ name: "CLS", value: 0.125, delta: 0.125, id: "v6-2" });
metrics.add({ name: "CLS", value: 0.25, delta: 0.125, id: "v6-2" }); // takes the first CLS's place
// The reader switches tabs: one beacon to /analytics, with the body
// [{"name":"LCP","value":1460,"delta":1460,"id":"v6-1"},{"name":"CLS","value":0.25,"delta":0.125,"id":"v6-2"}]
const beacon = useBeacon();
const metrics = createMetricQueue("/analytics");
const lcp = { name: "LCP", value: 1460, delta: 1460, id: "v6-1" };
const cls = { name: "CLS", value: 0.25, delta: 0.25, id: "v6-2" };
metrics.add(lcp);
metrics.add(cls);
expect(beacon.calls).toEqual([]);
setVisibility("hidden");
expect(beacon.calls.map((call) => call.url)).toEqual(["/analytics"]);
expect((await beacon.bodies()).map((body) => JSON.parse(body))).toEqual([[lcp, cls]]);
const beacon = useBeacon();
createMetricQueue("/analytics");
setVisibility("hidden");
setVisibility("visible");
setVisibility("hidden");
expect(beacon.calls).toEqual([]);
const beacon = useBeacon();
const metrics = createMetricQueue("/analytics");
const lcp = { name: "LCP", value: 1460, delta: 1460, id: "v6-1" };
const inp = { name: "INP", value: 88, delta: 88, id: "v6-3" };
metrics.add(lcp);
setVisibility("hidden");
metrics.add(inp);
setVisibility("visible");
expect(beacon.calls).toHaveLength(1);
setVisibility("hidden");
setVisibility("visible");
setVisibility("hidden");
expect((await beacon.bodies()).map((body) => JSON.parse(body))).toEqual([[lcp], [inp]]);
const beacon = useBeacon();
const metrics = createMetricQueue("/analytics");
const lcp = { name: "LCP", value: 1460, delta: 1460, id: "v6-1" };
const cls = { name: "CLS", value: 0.25, delta: 0.125, id: "v6-2" };
metrics.add({ name: "CLS", value: 0.125, delta: 0.125, id: "v6-2" });
metrics.add(lcp);
metrics.add(cls);
setVisibility("hidden");
expect((await beacon.bodies()).map((body) => JSON.parse(body))).toEqual([[cls, lcp]]);
const beacon = useBeacon();
const metrics = createMetricQueue("/analytics");
// A metrics library that reports CLS when the page is hidden, from a capture-phase listener, as web-vitals does.
const cls = { name: "CLS", value: 0.25, delta: 0.25, id: "v6-2" };
addEventListener("visibilitychange", () => {
if (document.visibilityState === "hidden") metrics.add(cls);
}, { capture: true });
setVisibility("hidden");
expect((await beacon.bodies()).map((body) => JSON.parse(body))).toEqual([[cls]]);
const beacon = useBeacon({ accept: false });
const network = useFetch(() => ({ status: 204 }));
const metrics = createMetricQueue("/analytics");
const lcp = { name: "LCP", value: 1460, delta: 1460, id: "v6-1" };
metrics.add(lcp);
setVisibility("hidden");
expect(beacon.calls.map((call) => call.accepted)).toEqual([false]);
expect(network.calls).toHaveLength(1);
const [call] = network.calls;
expect([call.url, call.method, call.keepalive]).toEqual(["/analytics", "POST", true]);
expect(JSON.parse(call.body)).toEqual([lcp]);
navigator.sendBeacon = undefined;
const network = useFetch(() => ({ status: 204 }));
const metrics = createMetricQueue("/analytics");
const inp = { name: "INP", value: 88, delta: 88, id: "v6-3" };
metrics.add(inp);
setVisibility("hidden");
expect(network.calls.map((call) => [call.url, call.method, call.keepalive])).toEqual([["/analytics", "POST", true]]);
expect(JSON.parse(network.calls[0].body)).toEqual([inp]);
Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.
Ctrl + Enter runs the tests (⌘ + Enter on a Mac).
I'm here to help with Send metrics when the page is hidden. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.