UNPKG

@rsc-kit/mcp

Version:

An MCP server over what an rsc-kit build decided: the routes, why each one is static or not, and what it costs the browser.

208 lines (161 loc) • 8.34 kB
# Web vitals > LCP, INP and CLS from real visitors, sent to an endpoint of your own. A lab score tells you how a page loads on one machine. Real visitors are on slower phones and worse networks, and their numbers are the ones Google ranks on. To collect them, install Google's `web-vitals` and put `<WebVitals>` in your root layout: ```sh bun add web-vitals ``` ```tsx title="src/app/layout.tsx" {2,8} import type { ReactNode } from 'react' import { WebVitals } from '@rsc-kit/core/web-vitals' export default function RootLayout({ children }: { children: ReactNode }) { return ( <html lang="en"> <body> <WebVitals endpoint="/api/vitals" /> {children} </body> </html> ) } ``` Every page now measures LCP, INP and CLS, with FCP and TTFB, and posts them to `/api/vitals` when the visitor leaves or switches tabs. Receive them in a [`route.ts`](/guides/api-routes/): ```ts title="src/app/api/vitals/route.ts" import type { VitalsBatch } from '@rsc-kit/core/web-vitals' export async function POST(request: Request) { const { path, navigations, metrics } = (await request.json()) as VitalsBatch for (const { name, value, rating, id } of metrics) { await db.insert(vitals).values({ id, name, value, rating, path, navigations, at: new Date() }) } return new Response(null, { status: 204 }) } ``` `<WebVitals>` renders nothing. It costs nothing until the page has loaded: see [How it loads](#how-it-loads). ## What is sent One `POST` each time the tab is hidden, with every metric measured since the last one: ```json { "path": "/posts/hello", "navigations": 0, "metrics": [ { "name": "LCP", "value": 1840.2, "rating": "good", "delta": 1840.2, "id": "v6-1764…", "navigationType": "navigate" }, { "name": "CLS", "value": 0.04, "rating": "good", "delta": 0.04, "id": "v6-1764…", "navigationType": "navigate" } ] } ``` - `value` is in milliseconds, except CLS, which has no unit. - `rating` is `good`, `needs-improvement` or `poor`, by Google's thresholds. - `path` is the page the visitor loaded. See [Client navigations](#client-navigations). - `navigationType` is how they arrived: `navigate`, `reload`, `back-forward`, `back-forward-cache`, `prerender` or `restore`. **Store by `id` and keep the last value.** CLS and INP can be sent again: a visitor who comes back to the tab and keeps scrolling makes a later, larger CLS for the same `id`. Counting both would count the page twice. A metric the browser cannot measure is not sent. CLS comes only from Chromium-based browsers, and LCP and INP only from browsers that have shipped their APIs, so each metric has its own number of samples. The request is a `navigator.sendBeacon`, which the browser delivers even as the page closes, or a `fetch` with `keepalive` where there is no beacon. Both send the visitor's cookies, so the endpoint can tell who it is hearing from. ## Sending to an analytics tool To send each metric somewhere else, such as Google Analytics, use the hook in a client component of your own and place that in the layout instead: ```tsx title="src/app/Analytics.tsx" 'use client' import { useWebVitals } from '@rsc-kit/core/web-vitals' export function Analytics() { useWebVitals((metric, { path }) => { gtag('event', metric.name, { value: Math.round(metric.name === 'CLS' ? metric.value * 1000 : metric.value), metric_id: metric.id, page_path: path, non_interaction: true, }) }) return null } ``` The callback is called with each metric as `web-vitals` reports it, the whole [`Metric`](https://github.com/GoogleChrome/web-vitals#metric) with its performance entries, and the page it was measured on. The tool does its own batching. ## Reading the numbers Look at the **75th percentile** of each metric, per page. That is the number Google judges a page by: three visits in four were at least that good. | Metric | Good, at p75 | Poor, above | Measures | | --- | --- | --- | --- | | LCP | 2.5 s | 4 s | when the largest thing in view was painted | | INP | 200 ms | 500 ms | how long the slowest interactions took to show a result | | CLS | 0.1 | 0.25 | how much the page moved under the visitor | | FCP | 1.8 s | 3 s | when anything was painted | | TTFB | 0.8 s | 1.8 s | when the first byte of the document arrived | ```sql -- the last value per id, then p75 per page, over the last 28 days select path, name, percentile_cont(0.75) within group (order by value) as p75, count(*) from (select distinct on (id) * from vitals where at > now() - interval '28 days' order by id, at desc) latest group by path, name order by path, name; ``` - An average hides the slow visits that p75 is there to show. Don't use one. - Compare phones and desktops apart if your endpoint records the user agent: most poor LCPs are on phones. - Search Console's numbers are Chrome's, over 28 days, from visitors who share usage data. Yours cover every browser that measures, so they will not match exactly. - A slow TTFB is the server or the network, before any of the page's own code runs. A good TTFB and a slow LCP is the page: an image without [priority](/guides/images/), a font, a script. ## Client navigations After the first page, a [navigation](/guides/navigation/) is not a page load: the document stays and the page inside it changes. The browser measures documents, so: - **LCP, FCP and TTFB** describe the page the visitor loaded, and are sent once. - **CLS and INP** keep counting for as long as the document lives, across every page the visitor moves to. `path` is always the page that was loaded, as in Chrome's own field data, and `navigations` counts the client navigations since. A batch with `navigations: 0` is about that page alone. One above 0 also holds the shifts and interactions of the pages visited after it: filter on `navigations = 0` to judge one page's CLS or INP on its own. Reports carry the path, not the route's pattern. The router in the browser asks the server for each page and never holds the route table. Group a dynamic route in your endpoint or your query, such as everything under `/posts/` together. A page restored from the back/forward cache is measured again, with `navigationType: 'back-forward-cache'` and `path` where the visitor returned to. Measuring LCP and INP per client navigation (soft navigations) is an experimental Chrome API, and `<WebVitals>` does not use it. ## The endpoint and the cross-site rule A `POST` to a `route.ts` that a browser sends from another site is [refused with 403](/guides/api-routes/#posts-from-another-site), by the browser's `Sec-Fetch-Site` header. A beacon to your own `endpoint` is `same-origin`, so it passes. `<WebVitals>` sends to your own origin only. To send to another service, use `useWebVitals` and that service's own client. The endpoint can live on any backend behind the same origin. It is an ordinary `POST` with a JSON body, and it must not ask for a CSRF token, which a beacon cannot send: - **Laravel:** a route in `routes/api.php`, which has no CSRF check. A route in `routes/web.php` answers the beacon with 419. - **Go:** an ordinary handler for `POST /api/vitals` that decodes the JSON body. ## How it loads `web-vitals` is a peer dependency of `@rsc-kit/core/web-vitals` and of nothing else. An app that never imports `<WebVitals>` or `useWebVitals` ships neither. An app that does ships about 1 KB gzipped with its layout, and the library, about 3.3 KB, as a file of its own. That file is requested after the page's `load` event and an idle moment, so it never competes with the page's own scripts or with hydration. Loading it late loses nothing: the browser keeps the paints and layout shifts since the navigation began, and the library reads them when it arrives. One thing is lost: a visit that leaves before the page finishes loading reports nothing. Measuring is Google's [`web-vitals`](https://github.com/GoogleChrome/web-vitals), the library Chrome's own field data is computed with, rather than a few `PerformanceObserver`s of our own. Each metric has rules that a short version gets wrong without saying so: LCP stops at the first input, CLS is the worst five-second burst of shifts rather than their sum, INP is a high percentile of all interactions, and a prerendered page counts from when it was shown.