10LOC

#timeouts

Node.jsintermediate

AbortController to cancel a fetch cleanly after a timeout

export const fetchWithTimeout = async (url: string, timeoutMs: number) => {
  const signal = AbortSignal.timeout(timeoutMs);
  try {
    const response = await fetch(url, { signal });
    return await response.text();

Use AbortSignal.timeout() to cancel a fetch after N milliseconds and tell a timeout apart from every other kind of failure.