Timeout and Retries

Configure automatic retries and request timeouts

Timeout

You can set the request timeout in milliseconds.

api.ts
import { createFetchClient } from "@zayne-labs/callapi";

const callBackendApi = createFetchClient({
	baseURL: "http://localhost:3000",
	timeout: 5000,
});

const result = await callBackendApi("/api/users", {
	timeout: 10000,
});

Auto Retry

For most use cases, you only need to specify the number of retry attempts:

api.ts
const result = await callApi("/api/users", {
	retryAttempts: 3,
});

Advanced Retry Options

CallApi provides flexible retry mechanisms with both linear and exponential backoff strategies.

Linear Retry Strategy

Waits a fixed amount of time between retries:

api.ts
const result = await callApi("/api/users", {
	retryStrategy: "linear",
	retryAttempts: 3,
	retryDelay: 1000,
});

Exponential Retry Strategy

Increases the delay between retries exponentially:

api.ts
const result = await callApi("/api/users", {
	retryStrategy: "exponential",
	retryAttempts: 5, // Retry up to 5 times
	retryDelay: 1000, // Start with 1 second delay
	retryMaxDelay: 10000, // Cap the delay at 10 seconds
	// Retry delays will be: 1s, 2s, 4s, 8s, 10s (capped at maxDelay)
});

RetryMethods and RetryStatusCodes

You can customize when to retry a request with the retryMethods and retryStatusCodes options.

  1. Retry Methods: This option allows you to specify which HTTP methods should be retried. By default, this option is set to ["GET", "POST"].This implies that only GET and POST requests will be retried by default.

  2. Retry Status Codes: This option allows you to specify which HTTP status codes should be retried. There are no default values for this option.

api.ts
const result = await callApi("/api/users", {
	retryStrategy: "linear",
	retryAttempts: 3,
	retryDelay: 1000,
	retryMethods: ["GET", "POST"],
	retryStatusCodes: [409, 425, 429, 500, 502, 503, 504],
});

Custom condition

Use retryCondition to implement custom retry logic:

api.ts
const result = await callApi("/api/users", {
	retryStrategy: "linear",
	retryAttempts: 3,

	retryCondition: ({ error, response }) => {
		return response?.status === 429; // Only retry on rate limit errors
	},
});

onRetry callback

Listen to retry attempts using the onRetry hook:

api.ts
const result = await callApi("/todos/1", {
	retryAttempts: 3,

	onRetry: (response) => {
		console.log(`Retrying request.`);
	},
});

Types

Timeout

Prop

Type

Retry

Prop

Type

Edit on GitHub

Last updated on

On this page