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

smart-fetch-retry

v1.1.0

Published

Una utilidad ligera para realizar peticiones fetch con reintentos automáticos y delay personalizable, compatible con Node.js y navegadores.

Readme

smart-fetch-retry

Una utilidad ligera para realizar peticiones HTTP con reintentos automáticos y soporte para Node.js y navegadores.
Perfecto para manejar solicitudes poco confiables, como llamadas a APIs externas que pueden fallar temporalmente.


✨ Características

  • ✅ Reintentos automáticos configurables
  • ✅ Delay personalizable entre cada intento
  • ✅ Compatible con fetch nativo y con node-fetch en Node.js
  • ✅ Manejo de errores detallado
  • ✅ Fácil de usar con async/await y también con .then()
  • ✅ Timeout configurable para cancelar peticiones automáticamente (nuevo en v1.1.0)
  • ✅ Cancelación de peticiones con AbortController (nuevo en v1.1.0)

📦 Instalación

npm install smart-fetch-retry

Nota: En Node.js 16+ se requiere instalar node-fetch si no existe soporte nativo de fetch:

npm install node-fetch

🚀 Uso

Ejemplo básico

import { smartFetchRetry } from "smart-fetch-retry";

const url = "https://api.escuelajs.co/api/v1/products";

async function main() {
  try {
    const { promise } = smartFetchRetry(url, { method: "GET" }, 3, 1500, 5000);
    const response = await promise;
    const data = await response.json();
    console.log("Datos recibidos:", data);
  } catch (error) {
    console.error("Error:", error.message);
  }
}

main();

⏱ Timeout automático

El último parámetro define el tiempo máximo (en milisegundos) antes de cancelar automáticamente la petición:

const { promise } = smartFetchRetry("https://api.example.com/data", {}, 3, 1500, 3000);

🛑 Cancelación manual

Puedes cancelar manualmente la petición usando controller.abort():

const { promise, controller } = smartFetchRetry("https://api.example.com/data", {}, 3, 1500, 5000);

promise
  .then(res => res.json())
  .then(data => console.log("Datos:", data))
  .catch(err => console.error("Error:", err.message));

setTimeout(() => {
  controller.abort();
  console.log("Petición cancelada manualmente");
}, 2000);

⚙️ Parámetros

| Parámetro | Tipo | Por defecto | Descripción | |------------|-----------|-------------|-----------------------------------------------------| | url | string | Requerido | URL de la petición. | | options | object | {} | Opciones para fetch (method, headers, body). | | retries | number | 3 | Número de intentos antes de fallar. | | delay | number | 1000 ms | Tiempo de espera entre cada intento (en ms). | | timeout | number | 5000 ms | Tiempo máximo antes de cancelar la petición automáticamente. |


🛠 Ejemplo con POST y Headers

const { promise } = smartFetchRetry(
  "https://api.example.com/data",
  {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ name: "John" }),
  },
  5,
  2000
);

const data = await response.json();
console.log(data);

❗ Manejo de errores

Si después de todos los reintentos la solicitud sigue fallando, la función lanza un error:

try {
  const { promise } = smartFetchRetry("https://api.fake.com/fail", {}, 2, 1000);
  await promise;
} catch (err) {
  console.error(err.message); // "Fallo después de 2 intentos: ..."
}

✅ Mejoras implementadas

  • [x] Cancelación con AbortController (implementado en v1.1.0).
  • [x] Soporte para timeout configurable (implementado en v1.1.0).

🧩 Próximas mejoras

  • [ ] Retraso exponencial para los reintentos.
  • [ ] Tipos para TypeScript.
  • [ ] Mejor manejo de logs en entorno de desarrollo.
  • [ ] Mejor manejo de errores específicos.

📄 Licencia

MIT © 2025 Miguel Ignacio González