Skip to main content

Plugins

Two small plugins on one client. The logger writes a line when a request starts and when it ends. The metrics plugin counts calls, errors and durations per endpoint, like an APM agent. Send a few requests and watch both fill in.

intermediatepluginssenderrors
import { useState, useSyncExternalStore } from "react";

import { calls, client, logger } from "./api";
import { logStore, metricsStore } from "./plugins";

type CallName = keyof typeof calls;
const callNames = Object.keys(calls) as CallName[];

const Log = () => {
const lines = useSyncExternalStore(logStore.subscribe, logStore.get);
return (
<article>
<h6>Logger plugin</h6>
{lines.length === 0 && <p className="muted">Send a request.</p>}
<ol className="log">
{lines.map((line) => (
<li key={line.id} className={line.kind}>
{line.text}
</li>
))}
</ol>
</article>
);
};

const Metrics = () => {
const metrics = useSyncExternalStore(metricsStore.subscribe, metricsStore.get);
const rows = Object.entries(metrics);
return (
<article>
<h6>Metrics plugin</h6>
<table>
<thead>
<tr>
<th>Endpoint</th>
<th>Calls</th>
<th>Error rate</th>
<th>Avg</th>
<th>Max</th>
</tr>
</thead>
<tbody>
{rows.map(([endpoint, stats]) => (
<tr key={endpoint}>
<td>
<code>{endpoint}</code>
</td>
<td>{stats.calls}</td>
<td className={stats.errors ? "error" : undefined}>{Math.round((stats.errors / stats.calls) * 100)}%</td>
<td>{Math.round(stats.totalMs / stats.calls)} ms</td>
<td>{stats.maxMs} ms</td>
</tr>
))}
</tbody>
</table>
{rows.length === 0 && <p className="muted">No requests finished yet.</p>}
</article>
);
};

export const App = () => {
const [loggerOn, setLoggerOn] = useState(true);

const toggleLogger = (on: boolean) => {
// Plugins can be added and removed at runtime. The metrics plugin keeps counting either way.
if (on) client.addPlugin(logger);
else client.removePlugin(logger);
setLoggerOn(on);
};

const sendMany = () => {
for (let index = 0; index < 8; index += 1) {
calls[callNames[index % callNames.length]]();
}
};

return (
<main className="container">
<hgroup>
<h1>Plugins</h1>
<p>Two plugins watch every request of the client: one logs it, one measures durations and error rates.</p>
</hgroup>
<div className="toolbar">
<div className="buttons">
{callNames.map((name) => (
<button key={name} type="button" className="outline" onClick={() => calls[name]()}>
{name}
</button>
))}
<button type="button" onClick={sendMany}>
Send 8 mixed
</button>
</div>
<label>
<input
type="checkbox"
role="switch"
checked={loggerOn}
onChange={(event) => toggleLogger(event.target.checked)}
/>
Logger plugin
</label>
</div>
<div className="grid-2">
<Log />
<Metrics />
</div>
</main>
);
};
Run locallynpx tiged BetterTyped/hyper-fetch/examples/react/plugins hyper-fetch-react-plugins && cd hyper-fetch-react-plugins && npm install && npm run dev
What it shows
  1. new Plugin({ name }) with chained hooks, wrapped in a function like loggerPlugin().
  2. onRequestStart and onRequestFinished run for every request of the client, successful or not.
  3. requestTimestamp and responseTimestamp on the response give the duration of each call.
  4. addPlugin and removePlugin turn a plugin on and off at runtime.

How it works​

  1. plugins.ts defines both plugins as functions that return a Plugin. Each hook method registers one callback and returns the plugin, so the hooks chain:

    new Plugin({ name: "logger" })
    .onRequestStart(({ request }) => writeLog(`→ ${request.method} ${request.endpoint}`, "start"))
    .onRequestFinished(({ request, response }) => { ... });
  2. onRequestFinished gets the request and the response, whatever the outcome. The duration is response.responseTimestamp - response.requestTimestamp.

  3. The metrics plugin groups by request.requestOptions.endpoint, the template such as /posts/:postId, so every id lands in one row. request.endpoint would be /posts/26.

  4. api.ts adds both plugins with client.addPlugin(). The requests themselves have no logging or metrics code.

  5. The Logger plugin switch calls client.removePlugin(logger) and client.addPlugin(logger). The metrics keep counting while the logger is off.

  6. The plugins write to two tiny stores, and App.tsx reads them with useSyncExternalStore. A real plugin would send the same data to a logging or analytics service instead.

Plugins only observe. A plugin that throws does not break the request. Calls that were deduplicated never reach the adapter, so they are not counted: GET requests are deduplicated by default, which is why two quick 500 error clicks count once.

When to use it
  • Logging, tracing and analytics that must cover every request without touching each one.
  • Performance budgets: alert when an endpoint gets slower or fails more often.
  • Debug tools that you add in development and leave out in production.

Summary

A plugin is a named object with lifecycle hooks. Added to the client with addPlugin, it sees the start and the end of every request, which is enough for logs, durations and error rates.