Repository navigation
Proposal: Exposing fetch metrics - count #4374
Replies: 1 comment 1 reply
|
A middleware recipe seems a good fit for the telemetry part. SWR already documents a fetcher-wrapping request logger, which is the right place to count actual fetcher invocations, rather than hook renders or revalidation requests. Two semantics are worth making explicit in this proposal:
For a non-reactive telemetry sink, this is a small starting point: import { unstable_serialize } from 'swr';
function createMetrics(report) {
const counts = new Map();
return useSWRNext => (key, fetcher, config) => {
const id = unstable_serialize(key);
const measured = fetcher && (async (...args) => {
const count = (counts.get(id) ?? 0) + 1;
counts.set(id, count);
const start = performance.now();
try {
return await fetcher(...args);
} finally {
report({ key: id, count, durationMs: performance.now() - start });
}
});
return useSWRNext(key, measured, config);
};
}Create that middleware once per cache/provider session, not during every render, and pass it through I checked this pattern with SWR 2.3.6 / React 18.3.1: two hooks sharing a key produced one initial event; an explicit same-data revalidation produced the second; a rejected attempt produced the third. The counter includes failures/retries, and measures fetcher duration, not necessarily HTTP wire requests: a fetcher may itself cache or make several requests. That definition also clarifies a native API proposal: specify whether counters belong to a hook, key, cache provider, or application session, and whether UI reactivity is part of the contract. I cannot speak for whether the maintainers plan to add it to core. |
Uh oh!
There was an error while loading. Please reload this page.
Background & Context
SWR is an exceptionally lightweight, performant, and reliable data-fetching library that has consistently been a go to choice for our modern React stack. Its minimalist API and focus on core cache revalidation principles make it a joy to work with.
The Problem
While scaling a production complex dashboard/application, I encountered a scenario where I needed to track the exact execution count of fetches for a given key.
Upon reviewing the official documentation, I noticed that SWR does not natively expose request metrics (like
fetchCountor retry attempt counters) A capability that libraries like TanStack Query offer out of the box.In large scale applications, enterprise dashboards, or performance monitoring setups, tracking fetch frequency and timing is crucial for:
To solve this in the short term, I had to write a custom React state/ref wrapper around
useSWRand the fetcher logic. While completely functional, it adds boilerplate that could ideally be handled more natively or cleanly.Proposal & Discussion
Given SWR’s design philosophy of keeping the core footprint minimal, I propose exploring one of the following approaches:
fetchCountcounter on theSWRResponseobject.swr/middlewareor documenting a standard pattern/recipe in the official docs for metric tracking.Custom Implementation Reference
For context, here is the lightweight wrapper pattern I implemented to handle this in userland:
All reactions