DEV Community

Željko Šević
Željko Šević

Posted on • Originally published at sevic.dev on

Timeout with Fetch API

Setting up a timeout for HTTP requests can prevent the connection from hanging forever, waiting for the response. It can be set on the client side to improve user experience, and on the server side to improve inter-service communication. Fetch API is fully available in Node as well from version 18.

AbortController can be utilized to set up timeouts. Instantiated abort controller has a signal property which represents reference to its associated AbortSignal object. Abort signal object is used as a signal parameter in the request with Fetch API, so HTTP request is aborted when abort method is called.

const HTTP_TIMEOUT = 3000;
const URL = 'https://www.google.com:81';

(async () => {
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), HTTP_TIMEOUT);

  try {
    const response = await fetch(URL, {
      signal: controller.signal
    }).then((res) => res.json());
    console.log(response);
  } catch (error) {
    console.error(error);
  } finally {
    clearTimeout(timeoutId);
  }
})();
Enter fullscreen mode Exit fullscreen mode

Use this snippet also to simulate aborted requests.

Boilerplate

Here is the link to the template I use for the development.

Top comments (2)

Collapse
 
_bkeren profile image
Collapse
 
zsevic profile image
Željko Šević

I updated the article with AbortController reference, thanks