Axios: How to Set Timeouts for Requests

Updated: February 10, 2023 By: Snowball Post a comment

In Axios, the default timeout is 0. This quick and straightforward article shows you a few ways to set custom timeouts when making HTTP requests with Axios.

Set Timeout for a single Request

You can set a timeout for an individual request like so:

try {
      const response = await axios('https://www.kindacode.com', {
        timeout: 5000, // Override the default timeout to 5 seconds
        method: 'GET',
      });
      console.log(response);
} catch (err) {
      console.log(err);
}

Or like this:

try {
      const response = await axios.post(
        'https://jsonplaceholder.typicode.com/posts',
        {
          title: 'foo',
          body: 'bar',
        },
        {
          timeout: 5000, // Override the default timeout for this request
          headers: {
            'Content-Type': 'application/json',
          },
        }
      );

      console.log(response.data);
} catch (error) {
      console.log(error);
}

Set a Timeout for multiple Requests

You can set a timeout for multiple requests by initializing an Axios instance. Here is an example:

// Create an axios instance
// and set the timeout for this instance
const client = axios.create({
      baseURL: 'https://jsonplaceholder.typicode.com',
      timeout: 3000, // 3 seconds
});

// make a GET request
try {
      const response = await client.get('/posts');
      console.log(response.data);
} catch (error) {
      console.log(error);
}

// make a POST request
try {
      const response = await client.post('/posts', {
        title: 'foo',
        body: 'bar',
        userId: 1,
      });
      console.log(response.data);
} catch (error) {
      console.log(error);
}

Further reading:

You can also check out our Javascript category page, TypeScript category page, Node.js category page, and React category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles