A fetch() wrapper with timeout and retry for WordPress scripts
fetch() has no timeout: on a bad mobile connection a request can hang for a minute while the spinner turns. It also does not repeat anything: one dropped packet or one 503 from an overloaded server, and the visitor sees an error. Both can be added in a small wrapper around fetch(), and the scripts of a theme or plugin call the wrapper instead.
Problem: The live search of a WordPress site calls the REST API with plain fetch(). On slow connections the search hangs without feedback, and when the server answers with 503 under load, the result list stays empty.
Solution: Wrap fetch() in a function that aborts each attempt after a timeout with AbortSignal.timeout(), repeats only safe requests (GET) after network errors and the status codes 408, 429, 502, 503 and 504, waits with exponential backoff and honors Retry-After, and still respects an outside AbortSignal so that a newer search can cancel an older one.
The wrapper
// js/ha-fetch.js
const RETRY_STATUS = new Set( [ 408, 429, 502, 503, 504 ] );
const sleep = ( ms ) => new Promise( ( resolve ) => setTimeout( resolve, ms ) );
export async function haFetch( url, { timeout = 8000, retries = 2, signal, ...options } = {} ) {
const method = ( options.method ?? 'GET' ).toUpperCase();
const canRetry = method === 'GET' || method === 'HEAD';
for ( let attempt = 0; ; attempt++ ) {
const timeoutSignal = AbortSignal.timeout( timeout );
const combined = signal ? AbortSignal.any( [ signal, timeoutSignal ] ) : timeoutSignal;
let response;
try {
response = await fetch( url, { ...options, signal: combined } );
} catch ( error ) {
if ( signal?.aborted ) throw error; // cancelled by the caller: stop
const isTimeout = error.name === 'TimeoutError';
if ( ! canRetry || attempt >= retries ) {
throw isTimeout ? new Error( `Timed out after ${ timeout } ms` ) : error;
}
await sleep( 2 ** attempt * 500 + Math.random() * 250 );
continue;
}
if ( response.ok ) {
return response;
}
if ( ! canRetry || attempt >= retries || ! RETRY_STATUS.has( response.status ) ) {
const body = await response.json().catch( () => ( {} ) );
const error = new Error( body.message ?? `HTTP ${ response.status }` );
error.status = response.status;
error.code = body.code;
throw error;
}
const retryAfter = Number( response.headers.get( 'Retry-After' ) );
await sleep( retryAfter > 0 ? Math.min( retryAfter, 30 ) * 1000 : 2 ** attempt * 500 + Math.random() * 250 );
}
}
What the details do:
AbortSignal.timeout()creates a signal that aborts after the given time; the error then has the nameTimeoutError. A new signal per attempt gives each attempt the full time.AbortSignal.any()combines it with the caller’s signal. When the caller aborts, the wrapper stops at once and does not retry.- POST, PUT and DELETE are never repeated automatically. If the first request reached the server and only the answer was lost, a repeat would save a form twice or create a second order.
- The random part of the delay (jitter) keeps many browsers from retrying at exactly the same moment after an outage.
- The wrapper returns the
Response; the caller decides whether it reads JSON, text or headers such asX-WP-Total.
Use it for the live search
import { haFetch } from './ha-fetch.js';
let controller;
async function haSearch( term ) {
controller?.abort(); // cancel the previous search
controller = new AbortController();
const url = new URL( window.haSearch.root + 'wp/v2/search' );
url.searchParams.set( 'search', term );
url.searchParams.set( 'per_page', '5' );
try {
const response = await haFetch( url, { timeout: 5000, signal: controller.signal } );
renderResults( await response.json() );
} catch ( error ) {
if ( error.name === 'AbortError' ) return; // a newer search is running
renderError( error.message );
}
}
window.haSearch.root is esc_url_raw( rest_url() ), passed from PHP. For a logged-in user’s request to a protected endpoint, add the header X-WP-Nonce with a wp_rest nonce in options.headers. The input handler should be debounced so that the search does not start on every key: debounce and throttle.
Saving data
await haFetch( window.haSearch.root + 'ha/v1/settings', {
method: 'POST',
timeout: 15000,
headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': window.haSearch.nonce },
body: JSON.stringify( settings ),
} );
A POST gets a longer timeout and no retry: if it fails, the interface shows the error and the user decides whether to save again.
NOTE: AbortSignal.any() is the newest part here: Chrome 116, Safari 17.4 and Firefox 124 (March 2024). For older browsers, combine the signals by hand: create one AbortController, call its abort() from a setTimeout and from an abort listener on the caller’s signal. How fetch replaces jQuery’s $.ajax in a theme in the first place: replace jQuery AJAX with fetch and AbortController. The same retry rules on the PHP side, for wp_remote_post(): wp_remote_post with error handling.