Skip to content

Instantly share code, notes, and snippets.

@imaginamundo
Last active August 7, 2025 17:28
Show Gist options
  • Save imaginamundo/88f54c97bb154044350ad831aaf4eb30 to your computer and use it in GitHub Desktop.
Save imaginamundo/88f54c97bb154044350ad831aaf4eb30 to your computer and use it in GitHub Desktop.
A wrapper for fetch with timeout using abort controller and a specific timeout error with url and status.
const DEFAULT_TIMEOUT = 3000;
function request(resource, options = {}) {
const { timeout = DEFAULT_TIMEOUT } = options;
delete options.timeout;
return fetch(resource, { ...options, signal: AbortSignal.timeout(timeout) });
}
export default request;
interface RequestOptions extends RequestInit {
timeout?: number;
}
const DEFAULT_REQUEST_TIMEOUT = 3000;
function request(
resource: RequestInit | URL,
options: RequestOptions & { timeout?: number } = {}
): Promise<Response> {
const { timeout = DEFAULT_TIMEOUT } = options;
delete options.timeout;
return fetch(resource, { ...options, signal: AbortSignal.timeout(timeout) });
}
export default request;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment