Node.js: Simple request timeout with fetch()

The code snippet below tells fetch() to abort the request when it takes longer than the specified amount of time. It is only one line!

Previously you had to define an AbortSignal controller and implement a setTimeout() that would call the abort() function on the controller. And then all kinds of error catching to understand what triggered the abort. With the new method AbortSignal.timeout() you can do all of this at once. It will throw when the timeout is met before the request is resolved.

  1. Add this to the fetch() options argument:
  2. Example
  3. Notes

Add this to the fetch() options argument:

  signal: AbortSignal.timeout( ms ),


 * @param   {string}  url
 * @param   {number}  [timeout=5000]  Request timeout in ms
 * @return  {Promise}

async function httpGet ( url, timeout = 5000 ) {
  const res = await fetch( url, {
    signal: AbortSignal.timeout( timeout ),
  } );

  return res.json();
// Timeout after 100 ms
httpGet( 'https://domain.tld/', 100 )
  .then( doSomething )
  .catch( err => console.log( ) )  // TimeoutError


  • Node.js version >= 17.3.0 is required. It may also work in recent browsers.

Like this article?
Buy me a choco

Related stuff

Leave a Comment

Your email address will not be published. Required fields are marked *