DEV Community

Željko Šević
Željko Šević

Posted on • Originally published at sevic.dev on

HTTP timeout with Axios

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.

axios package provides a timeout parameter for this functionality.

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

(async () => {
  try {
    await axios(URL, {
      timeout: HTTP_TIMEOUT,
    });
  } catch (error) {
    console.error('Request timed out', error.cause);
  }
})();
Enter fullscreen mode Exit fullscreen mode

Use this snippet also to simulate aborted requests.

Demo

The demo with the mentioned example is available here.

Top comments (0)