The URL to fetch.
Fetch options.
Timeout in milliseconds (default: 10000).
A promise that resolves to the fetch Response.
export async function fetchWithTimeout(
url: string,
options: RequestInit = {},
timeout = 10000,
): Promise<Response> {
const controller = new AbortController();
const { signal } = controller;
const timeoutId = setTimeout(() => controller.abort(), timeout);
try {
const response = await fetch(url, {
...options,
signal,
});
if (!response.ok) {
throw response;
}
return response;
} catch (error) {
// AbortError is caused by our timeout
if (error instanceof Error && error.name === "AbortError") {
const timeoutError = new Error("Request timed out");
timeoutError.name = "TimeoutError";
throw timeoutError;
}
throw error;
} finally {
clearTimeout(timeoutId);
}
}
Performs a network request with a timeout.