npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

better-isomorphic-fetch

v0.0.1

Published

A drop-in `fetch` replacement with **retries**, **exponential backoff**, and **OpenTelemetry tracing** — zero config required.

Readme

better-isomorphic-fetch

A drop-in fetch replacement with retries, exponential backoff, and OpenTelemetry tracing — zero config required.

  • Same fetch(url, init) signature you already know
  • Exponential backoff with jitter, Retry-After support, abort signal awareness
  • Safe defaults: only idempotent methods are retried, only transient status codes trigger retries
  • Automatic OpenTelemetry spans, trace propagation, and Server-Timing parsing on Node.js (opt-in)
  • Uses undici request on Node.js, native fetch in the browser

Install

pnpm add better-isomorphic-fetch

@opentelemetry/api is an optional peer dependency — install it to enable automatic tracing on Node.js.

pnpm add @opentelemetry/api

Quick start

import { fetch } from "better-isomorphic-fetch";

const response = await fetch("https://api.example.com/data", {
  retries: 3,
  retryDelay: 500,
});

That's it. If the request fails with a 503, it retries up to 3 times with exponential backoff starting at 500ms. Everything else works exactly like fetch.

Options

better-isomorphic-fetch extends the standard RequestInit with retry configuration:

interface BetterFetchInit extends RequestInit {
  retries?: number;
  retryDelay?: number;
  retryOn?: number[];
  retryMethods?: string[];
  onRetry?: (info: {
    attempt: number;
    error: Error | null;
    response: Response | null;
    delay: number;
  }) => boolean | void | Promise<boolean | void>;
}

| Option | Default | Description | |---|---|---| | retries | 0 | Number of retry attempts. 0 means no retries (standard fetch behavior). | | retryDelay | 1000 | Base delay in milliseconds. Actual delay uses exponential backoff with jitter: delay * 2^attempt + random jitter. | | retryOn | [408, 429, 500, 502, 503, 504] | HTTP status codes that trigger a retry. | | retryMethods | ["GET", "HEAD", "OPTIONS", "PUT"] | HTTP methods eligible for retry. POST is excluded by default to prevent duplicate side effects. | | onRetry | — | Hook called before each retry. Return false to abort. |

Examples

Basic retry

import { fetch } from "better-isomorphic-fetch";

const res = await fetch("https://api.example.com/users", {
  retries: 3,
});

Custom retry behavior

const res = await fetch("https://api.example.com/webhook", {
  method: "POST",
  body: JSON.stringify({ event: "deploy" }),
  retries: 5,
  retryDelay: 200,
  retryMethods: ["POST"],       // opt POST into retries
  retryOn: [429, 502, 503],     // only retry on these codes
});

Logging retries

const res = await fetch("https://api.example.com/data", {
  retries: 3,
  retryDelay: 1000,
  onRetry: ({ attempt, error, response, delay }) => {
    console.log(
      `Retry ${attempt} in ${delay}ms`,
      response ? `status=${response.status}` : error?.message,
    );
  },
});

Aborting retries early

Return false from onRetry to stop retrying immediately:

const res = await fetch("https://api.example.com/data", {
  retries: 10,
  onRetry: ({ attempt, response }) => {
    if (response?.status === 401) return false; // don't retry auth errors
  },
});

With AbortSignal

const controller = new AbortController();
setTimeout(() => controller.abort(), 5000);

const res = await fetch("https://api.example.com/slow", {
  retries: 3,
  signal: controller.signal,
});

The signal is checked between retries — if aborted during the backoff sleep, the fetch throws immediately.

Retry behavior

Exponential backoff with jitter. Delay doubles each attempt with 20% random jitter to prevent thundering herd:

Attempt 1: retryDelay * 2^0 + jitter  →  ~1000ms
Attempt 2: retryDelay * 2^1 + jitter  →  ~2000ms
Attempt 3: retryDelay * 2^2 + jitter  →  ~4000ms

Retry-After header. On 429 responses, the Retry-After header is respected (both seconds and HTTP-date formats). The delay is clamped to the max backoff to prevent unbounded waits.

Connection cleanup. Response bodies are cancelled between retries to free connections.

Method safety. Only idempotent methods are retried by default. Override with retryMethods when you know it's safe.

OpenTelemetry (Node.js)

When @opentelemetry/api is installed and a tracer provider is configured, every fetch automatically produces a client span:

HTTP GET
├─ http.request.method: GET
├─ url.full: https://api.example.com/data
├─ server.address: api.example.com
├─ server.port: 443
├─ http.response.status_code: 200
├─ http.resend_count: 2              ← only if retries occurred
├─ http.server_timing.cache.duration: 2.5
├─ http.server_timing.db.duration: 53.2
└─ events:
   ├─ http.retry { attempt: 1, status_code: 503, delay_ms: 1020 }
   └─ http.retry { attempt: 2, status_code: 503, delay_ms: 2180 }

Features:

  • Client spans with semantic HTTP attributes
  • W3C Trace Context propagation on outgoing headers
  • http.retry events with attempt number, delay, status code, and error
  • http.resend_count attribute when retries occurred
  • Server-Timing header parsed into http.server_timing.<name>.duration and http.server_timing.<name>.description attributes
  • Error recording — 5xx responses set span status to ERROR; exceptions are recorded

No OpenTelemetry? No problem — the library works identically without it. The import is lazy and failure is silent.

Browser vs Node.js

The package uses conditional exports:

| Environment | Implementation | OTel | |---|---|---| | Node.js | undici request() | Yes (when @opentelemetry/api is installed) | | Browser | globalThis.fetch | No |

Both environments get the same retry behavior. The split is handled automatically by your bundler or runtime.

License

MIT