Spoosh
Plugins

Retry

Automatic retry on failure

The retry plugin automatically retries failed requests with configurable attempts and delay.

Installation

npm install @spoosh/plugin-retry

Usage

import { Spoosh } from "@spoosh/core";
import { retryPlugin } from "@spoosh/plugin-retry";

const spoosh = new Spoosh<ApiSchema, Error>("/api").use([
  retryPlugin({ retries: 3, retryDelay: 1000 }),
]);

Retry Behavior

By default, the plugin retries on:

  • Network errors - Always retried (cannot be disabled via shouldRetry)
  • Status codes - 408, 429, 500, 502, 503, 504

Per-Request Override

// More retries for critical requests
useRead((api) => api("important").GET(), {
  retry: { retries: 5, delay: 2000 },
});

// Disable retries for specific requests
useRead((api) => api("health").GET(), {
  retry: { retries: false },
});

Custom Retry Logic

Use the shouldRetry callback for custom retry conditions:

import { retryPlugin, ShouldRetryCallback } from "@spoosh/plugin-retry";

const shouldRetry: ShouldRetryCallback = ({ status, attempt }) => {
  // Only retry on 503 Service Unavailable
  return status === 503;
};

const spoosh = new Spoosh<ApiSchema, Error>("/api").use([
  retryPlugin({ retries: 3, shouldRetry }),
]);

// Per-request override
useRead((api) => api("posts").GET(), {
  retry: {
    shouldRetry: ({ status }) => status === 429,
  },
});

Network errors are always retried regardless of the shouldRetry callback return value.

Options

Plugin Config

OptionTypeDefaultDescription
retriesnumber | false3Number of retry attempts. Set to false to disable.
retryDelaynumber1000Delay between retries in milliseconds (uses exponential backoff)
shouldRetryShouldRetryCallbackRetries on 408, 429, 500, 502, 503, 504Custom callback to determine if a request should be retried

Per-Request Options

Pass options via the retry object:

OptionTypeDescription
retriesnumber | falseOverride retry attempts for this request
delaynumberOverride retry delay for this request
shouldRetryShouldRetryCallbackOverride retry logic for this request

ShouldRetryContext

The shouldRetry callback receives a context object:

PropertyTypeDescription
statusnumber?HTTP status code from the response
errorunknownThe error that occurred
attemptnumberCurrent attempt number (0-indexed)
maxRetriesnumberMaximum number of retries configured

On this page