@cedvict/http-guardian
Core HTTP client (Promises) built on fetch.
Install
Runtime requirement: Node >= 22 (or any modern browser/edge runtime with fetch).
If you run in an environment without a global fetch, pass one explicitly via createHttpClient({ fetch }).
Prereleases (0.0.1-next.*) are published on the next dist-tag. Until a
stable version is out, latest points to an older prerelease: install from
next, or pin the exact version.
npm i @cedvict/http-guardian@next
Quick example (REST classic envelope)
import { createHttpClient, bearerAuth, createApiParserRestClassic, memoryCache } from "@cedvict/http-guardian";
const api = createHttpClient({
baseUrl: "https://api.example.com",
auth: bearerAuth(() => localStorage.getItem("token")),
parser: createApiParserRestClassic(),
cache: memoryCache({ maxEntries: 500 })
});
const res = await api.get<{ id: string; name: string }>("/me", {
cache: { ttlMs: 30_000, tags: ["me"] }
});
if (res.ok) console.log(res.data.name);
else console.error(res.errors);
Binary responses
Use an explicit response type for downloads. Successful responses bypass the JSON envelope parser so their bytes stay intact. Error responses still use the normal content-type decoder, which preserves structured API errors.
const report = await api.get<Blob>("/reports/monthly", {
responseType: "blob",
headers: { accept: "application/pdf" },
});
if (report.ok) {
const url = URL.createObjectURL(report.data);
// Open or download the URL, then call URL.revokeObjectURL(url).
} else {
console.error(report.errors);
}
responseType: "arrayBuffer" is also available for byte-oriented processing.
Binary requests do not receive the default Accept: application/json header,
and cache/deduplication keys keep blob and arrayBuffer responses separate.
Presets
createApiParserRestClassic()createApiParserLaravel()createApiParserNest()createApiParserGraphQL({ allowPartialData? })createApiParserStructured({ exposeMeta?, honorRetryableHint? })— parser pour une enveloppe structurée typée :{ success, code, message, details, retryable, issues[], i18n, meta }. En cas d'erreur, chaqueAppErrorportecode,messageet le booléen typéretryable. Les détails backend et les champs structurés (category,severity,i18n,traceId,spanId,envelope) restent disponibles dansdetails. Une issue peut remplacer l'indicationretryablede l'enveloppe.createApiParserProblem({ codeMembers?, requestIdHeader? })— Problem Details (RFC 9457,application/problem+json). Message fromdetail, elsetitle;codefrom the first non-blank member ofcodeMembers(default["code"], e.g.["rule", "code"]); every extension kept indetails.extensions(ProblemErrorDetails), withretryAfter(theRetry-Afterheader) andrequestId. A booleanretryablemember becomesAppError.retryable. Validation problems give oneAppErrorper input, fromerrors({ detail, pointer }) orinvalid-params({ name, reason }).createApiParserDetail({ requestIdHeader? })— APIs without success envelope: the success body is the data, errors are{ detail, code?, retryAfter?, requestId? }. A stringdetailgives oneAppError(codekept); a 422 validationdetailarray gives oneAppErrorper input, withfield(locwithout itsbody/query/... source) andcode(the issuetype).details(DetailErrorDetails) carriesretryAfter(theRetry-Afterheader, delay or HTTP date, else the body field, in whole seconds),requestId(body, elseX-Request-ID),locand the rawbody.
A parser may read the headers of a failed response: getErrors(raw, status, response?) receives { headers } as an optional third argument.
Without a notifier, the client uses consoleNotifier, which writes every
failure to the console. Pass silentNotifier when the application shows its
own messages from result.errors.
Auth modes
bearerAuth(() => token)cookieAuth({ credentials: "include", csrf: { headerName, getToken } })noAuth()
Guards
Les guards composent un middleware autour de chaque requête.
bearerRefreshGuard({ refreshFn, onAuthFailed?, ... })
Refresh JWT Bearer single-flight : sur 401, un seul refreshFn() est invoqué ;
toutes les autres requêtes 401 reçues pendant ce refresh attendent dans une queue
partagée puis sont rejouées avec le nouveau token. Si le refresh échoue,
onAuthFailed(error) est appelé une seule fois et toutes les requêtes en queue
voient le 401 d'origine.
import { createHttpClient, bearerAuth, bearerRefreshGuard } from "@cedvict/http-guardian";
createHttpClient({
auth: bearerAuth(() => tokenStore.access()),
guards: [
bearerRefreshGuard({
refreshFn: async () => {
const { accessToken, refreshToken } = await api.refresh();
tokenStore.set(accessToken, refreshToken);
return { accessToken, refreshToken };
},
onAuthFailed: () => router.navigate("/login"),
skipRefreshFor: (ctx) => ctx.url.includes("/auth/"),
}),
],
});
csrfGuard({ tokenFromCookie?, tokenFromStorage?, tokenFromHeader?, headerName?, applyTo? })
Injecte un header X-CSRF-Token (défaut) sur les méthodes mutantes
(POST/PUT/PATCH/DELETE). SSR-safe : si tokenFromCookie est utilisé
hors browser (typeof document === 'undefined'), le guard skippe silencieusement.
csrfGuard(
isPlatformBrowser(platformId)
? { tokenFromCookie: "csrf_token" }
: { tokenFromStorage: () => null },
);
correlationIdGuard({ headerName?, generator?, readResponseHeader? })
Injecte un header X-Correlation-Id (UUID v4 par défaut, fallback
Math.random()+timestamp si crypto.randomUUID absent). L'ID est stable
entre retries (mémorisé sur le ctx). Si la réponse contient le même header,
il est copié dans ctx.meta.correlationId pour les plugins downstream
(logger, sentry, otel).
💡 Pattern "X-Request-Id" : si ton backend (ops, ELK, Datadog…) utilise le header
X-Request-Idplutôt queX-Correlation-Idpour stitcher les logs front/back, change justeheaderName:correlationIdGuard({ headerName: "X-Request-Id" })Pas besoin d'OpenTelemetry côté front, ni d'un second guard : c'est le même mécanisme avec un nom différent. Combinable avec un OTel
traceparent: les deux headers coexistent sans conflit.
idempotencyGuard({ headerName?, applyTo?, respectExisting? })
Injecte un header X-Idempotency-Key (UUID par défaut) sur POST/PUT/PATCH.
La clé est stable entre retries — sinon l'idempotence côté serveur est cassée.
Respecte une clé fournie via RequestOptions.idempotencyKey,
ctx.idempotencyKey, ou directement via header.
Recipe : mapper le traceId backend ↔ Sentry / OTel frontend
Quand le backend renvoie une enveloppe avec un meta.traceId (et spanId)
— typiquement via createApiParserStructured — il est utile de stitcher cette
trace avec le span/event front-end pour qu'un incident Sentry pointe directement
vers la trace backend correspondante (et inversement).
Le pattern repose sur deux briques :
correlationIdGuardgénère unX-Correlation-Idpropagé sur la requête, et lit le header de réponse pour exposer l'ID dansctx.meta.correlationId.createApiParserStructuredstocketraceId/spanIddanserrors[].details(en cas d'erreur). Pour les chemins succès, on lit le header de réponse via un petit guard dédié.
import {
createHttpClient,
bearerAuth,
correlationIdGuard,
createApiParserStructured,
type Guard,
} from "@cedvict/http-guardian";
import { sentryPlugin } from "@cedvict/http-guardian-plugin-sentry";
import { otelPlugin } from "@cedvict/http-guardian-plugin-otel";
import * as Sentry from "@sentry/browser";
// Lit X-Trace-Id / X-Span-Id de la réponse et les pose sur ctx.meta pour
// les plugins downstream (sentry, otel, logger).
const traceMetaGuard: Guard = async (ctx, next) => {
const res = await next(ctx);
const traceId = res.headers.get("x-trace-id");
const spanId = res.headers.get("x-span-id");
if (traceId || spanId) {
ctx.meta ??= {};
if (traceId) ctx.meta.traceId = traceId;
if (spanId) ctx.meta.spanId = spanId;
}
return res;
};
const api = createHttpClient({
baseUrl: "https://api.example.com",
auth: bearerAuth(() => token),
parser: createApiParserStructured(),
guards: [correlationIdGuard(), traceMetaGuard],
plugins: [
sentryPlugin({
// shouldCapture reçoit le ctx → on lit ctx.meta pour tagger l'event Sentry.
shouldCapture: ({ status, ctx }) => {
if (status && status >= 500) {
Sentry.getCurrentScope().setTags({
"backend.trace_id": ctx.meta?.traceId ?? "",
correlation_id: ctx.meta?.correlationId ?? "",
});
return true;
}
return false;
},
}),
otelPlugin({
setAttributes: (span, ctx) => {
if (ctx.meta?.traceId) span.setAttribute("backend.trace_id", ctx.meta.traceId);
if (ctx.meta?.spanId) span.setAttribute("backend.span_id", ctx.meta.spanId);
if (ctx.meta?.correlationId) span.setAttribute("correlation_id", ctx.meta.correlationId);
},
}),
],
});
Côté erreur, l'enveloppe parsée par createApiParserStructured expose déjà
traceId / spanId dans result.errors[0].details :
const r = await api.post("/orders", { json: payload });
if (!r.ok) {
const d = r.errors[0]?.details as { traceId?: string; spanId?: string } | undefined;
console.error("backend trace:", d?.traceId, d?.spanId);
}
Redirects
redirects: { mode: "follow" | "manual" | "error", maxHops, onRedirect }
Testing
See TESTING.md.
Cookie session refresh guard (single-flight, cooldown, anti-loop)
If you use cookie-based auth and your backend exposes a refresh endpoint, you can add the safe refresh guard:
import { createHttpClient, cookieAuth, cookieSafeRefreshGuard, createApiParserRestClassic } from "@cedvict/http-guardian";
const api = createHttpClient({
baseUrl: "https://api.example.com",
auth: cookieAuth({ credentials: "include" }),
parser: createApiParserRestClassic(),
guards: [
cookieSafeRefreshGuard({
refreshPath: "/auth/refresh", // or absolute: "https://auth.example.com/refresh"
maxRetry: 1, // anti-loop (default)
honorRetryAfter: true // cooldown on 429 (default)
})
],
});
You can disable any auth/refresh behavior per-request with noAuth: true:
await api.get("/public/health", { noAuth: true });
Notifier redaction (optional)
If you provide a custom notifier and it logs/sends events to telemetry, you can add a redact function
to strip secrets from the event payload (e.g. query params in url):
import type { Notifier, NotifyEvent } from "@cedvict/http-guardian";
const notifier: Notifier = {
redact: (e: NotifyEvent) => ({ ...e, url: e.url.replace(/\?.*$/, "") }),
notify: (e) => console.error(e),
};
Preset builder & aliases (stable DX)
If you want a 1-liner setup without losing access to createHttpClient, use the preset builder:
import { createPresetBuilder } from "@cedvict/http-guardian";
const api = createPresetBuilder({ baseUrl: "https://api.example.com" })
.cookie({ credentials: "include" })
// opt-in only:
// .cookieRefresh({ refreshPath: "/auth/refresh", mePath: "/auth/me" })
.create();
Aliases (thin wrappers around the preset builder):
createCookieClient({ baseUrl, refresh?: CookieSafeRefreshGuardOptions | null, ... })createBearerClient({ baseUrl, getToken, ... })
Stable auth refresh policy
- Cookie auth: refresh is opt-in (add
cookieRefresh(...)or passrefreshtocreateCookieClient). - Bearer auth: refresh is disabled by default.
Plugins (config-time)
plugins are applied synchronously during createHttpClient(...) to mutate a draft options object.
Contract:
- Applied in order
- De-duplicated by
name(first wins)