Node.js: Simple fetch() timeout

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 ),
}

Example

// Timeout after 100 ms
fetch( 'https://domain.tld/', {
  signal: AbortSignal.timeout( 100 ),
} )
  .then( doSomething )
  .catch( err => console.log( err.name ) )
  // "TimeoutError"

Notes

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

Like this article?
Buy me a coffee


Related stuff


Comments

Leave a Reply

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