6.0.0 • Published 12 days ago

fetch-retry v6.0.0

Weekly downloads
73,313
License
MIT
Repository
github
Last release
12 days ago

fetch-retry

Adds retry functionality to the Fetch API.

It wraps any fetch API package (eg: isomorphic-fetch, cross-fetch, isomorphic-unfetch, or Node.js native's fetch implementation) and retries requests that fail due to network issues. It can also be configured to retry requests on specific HTTP status codes.

Node.js CI

npm package

npm install fetch-retry --save

Example

fetch-retry is used the same way as fetch, but also accepts retries, retryDelay, and retryOn on the options object.

These properties are optional, and unless different defaults have been specified when requiring fetch-retry, these will default to 3 retries, with a 1000ms retry delay, and to only retry on network errors.

const originalFetch = require('isomorphic-fetch');
const fetch = require('fetch-retry')(originalFetch);

// fetch-retry can also wrap Node.js's native fetch API implementation:
const fetch = require('fetch-retry')(global.fetch);
fetch(url, {
    retries: 3,
    retryDelay: 1000
  })
  .then(function(response) {
    return response.json();
  })
  .then(function(json) {
    // do something with the result
    console.log(json);
  });

or passing your own defaults:

const originalFetch = require('isomorphic-fetch');
const fetch = require('fetch-retry')(originalFetch, {
    retries: 5,
    retryDelay: 800
  });

fetch-retry uses promises and requires you to polyfill the Promise API in order to support Internet Explorer.

Example: Exponential backoff

The default behavior of fetch-retry is to wait a fixed amount of time between attempts, but it is also possible to customize this by passing a function as the retryDelay option. The function is supplied three arguments: attempt (starting at 0), error (in case of a network error), and response. It must return a number indicating the delay.

fetch(url, {
    retryDelay: function(attempt, error, response) {
      return Math.pow(2, attempt) * 1000; // 1000, 2000, 4000
    }
  }).then(function(response) {
    return response.json();
  }).then(function(json) {
    // do something with the result
    console.log(json);
  });

Example: Retry on 503 (Service Unavailable)

The default behavior of fetch-retry is to only retry requests on network related issues, but it is also possible to configure it to retry on specific HTTP status codes. This is done by using the retryOn property, which expects an array of HTTP status codes.

fetch(url, {
    retryOn: [503]
  })
  .then(function(response) {
    return response.json();
  })
  .then(function(json) {
    // do something with the result
    console.log(json);
  });

Example: Retry custom behavior

The retryOn option may also be specified as a function, in which case it will be supplied three arguments: attempt (starting at 0), error (in case of a network error), and response. Return a truthy value from this function in order to trigger a retry, any falsy value will result in the call to fetch either resolving (in case the last attempt resulted in a response), or rejecting (in case the last attempt resulted in an error).

fetch(url, {
    retryOn: function(attempt, error, response) {
      // retry on any network error, or 4xx or 5xx status codes
      if (error !== null || response.status >= 400) {
        console.log(`retrying, attempt number ${attempt + 1}`);
        return true;
      }
    })
    .then(function(response) {
      return response.json();
    }).then(function(json) {
      // do something with the result
      console.log(json);
    });

Example: Retry custom behavior with async

The retryOn option may also be used with async and await for calling asyncronous functions:

fetch(url, {
    retryOn: async function(attempt, error, response) {
      if (attempt > 3) return false;

      if (error !== null) {
        var json = await response.json();
        if (json.property !== undefined) {
          return true;
        }
      }
    })
    .then(function(response) {
      return response.json();
    }).then(function(json) {
      // do something with the result
      console.log(json);
    });
fsa-duxownup-analytics@procdev/client@saaspe/components@everything-registry/sub-chunk-1660no-install-puppeteermomenticm3u8-playlist-clonem3u8-dash-clonemetalsmith-cockpitmanifest-confusion-checknovacap-components@uniformdev/canvas-sitecore@skedulr/nebula-ui-library@twilio-labs/runtime-helpers@webtor/platform-sdk-js@zalastax/nolb-fet@vtex/gatsby-source-cms@vtex/client-cms@vtex/gatsby-plugin-cms@wacoco/yaction-package-deployagol-cache@amazeelabs/gatsby-source-silverback@asteroid-protocol/sdk@accentor/api-client-jsappcharge-checkoutappcharge-checkout-reactjs-sdk@automattic/vip@alephium/cli@axiomhq/js@axie-taxi/core@colony/eventscloudflare-kv-storage-rest@batbayar/superset-plugin-chart-hello-world@cs125/personable@cs125/questionable@cs125/questioner@cyzeal/fetch-onion-modelcanvas-video-next@cagov/github-tree-push@cagov/slack-connector@cagov/wordpress-to-github@cagov/11ty-serverless-preview-mode@ghuser/github-contribsnpm-all-packagesomnipartnersquran-dloso-cloudpolyglot-component-libraryreact-form-component-libraryparvan_componentsparvan_reactjs_componentsopenvsx-webuireact-cimpress-commentsemantic-release-npm-workspaces-monoreposentry-source-maps-webpack-pluginservicebotzy-blogapixminds-sdk-nodejsumbrella-http-clienttrack-trace-toolstype-libaryyahoo-finance-moduletesting-storybooktita-superset-chartshainasokisnapletsuperset-plugin-chart-hello-world2rtd-bottest-jcbr-sdksciolyffreact-tiktok@charmverse/core@chalii/utils@hyperlog/github-contribs@ibm-generative-ai/node-sdk@img-arena/img-ui-mui-theme@img-arena/ui-core@dimcheify/dimui@digitalrakesh/jsui@adobe/wskdebugattrace-network-js@equilogic/honeycomb-shared@eservices/servicebot@expertbridge-ui/connection@expertbridge-ui/core@expertbridge-custom/core@expo/rudder-sdk-node@fm-superset-ui/core@honeybadger-io/plugin-core@honeybadger-io/rollup-plugindsokal-rudder-sdk-node@adobe/aio-lib-core-networking@adobe/content-lake-commons@adobe/helix-mediahandler3s-toolsescalade-data-storeescalade-price-store
6.0.0

12 days ago

5.0.6

11 months ago

5.0.5

11 months ago

5.0.4

1 year ago

5.0.3

2 years ago

5.0.2

2 years ago

5.0.1

3 years ago

5.0.0

3 years ago

4.1.1

3 years ago

4.1.0

3 years ago

4.0.1

4 years ago

4.0.0

4 years ago

3.2.3

4 years ago

3.2.2

4 years ago

3.2.1

4 years ago

3.1.0

4 years ago

3.0.1

4 years ago

3.0.0

4 years ago

2.2.3

5 years ago

2.2.2

5 years ago

2.2.1

5 years ago

2.2.0

5 years ago

2.1.0

5 years ago

2.0.0

6 years ago

1.2.1

6 years ago

1.2.0

6 years ago

1.1.1

7 years ago

1.1.0

7 years ago

1.0.3

7 years ago

1.0.2

7 years ago

1.0.1

7 years ago

0.1.1

7 years ago

0.0.5

8 years ago

0.0.4

8 years ago

0.0.3

8 years ago

0.0.2

8 years ago

0.0.1

8 years ago