How to handle Timeouts when using Axios [3 easy Ways]

avatar
Borislav Hadzhiev

Last updated: Apr 4, 2024
5 min

banner

# Table of Contents

  1. How to handle Timeouts when using Axios
  2. Setting the timeout property for multiple requests
  3. The axios timeout property is for response timeouts, not connection timeouts

# How to handle Timeouts when using Axios

Make sure you have axios installed to be able to run the code samples.

shell
npm init -y # install using NPM npm install axios # or install using YARN yarn add axios
By default, the timeout in axios is set to 0, which means there is no timeout and requests won't get aborted after a certain period of time.

This is most likely not what you want.

You can set the timeout property in the request config object when issuing an axios request to handle timeouts when using axios.

The timeout property specifies the number of milliseconds before the request times out.

index.js
import axios from 'axios'; // ๐Ÿ‘‡๏ธ if you use CommonJS require() // const axios = require('axios'); async function getPosts() { try { const response = await axios.get( 'https://jsonplaceholder.typicode.com/posts', { timeout: 3000, headers: { Accept: 'application/json', }, }, ); return response.data; } catch (err) { if (err.code === 'ECONNABORTED') { console.log('The request timed out.'); } else { console.log(err); } } } getPosts().then(result => { console.log(result); });

set timeout when using axios

The code for this article is available on GitHub

We set the timeout property to 3000 milliseconds in the request config object.

The timeout specifies the number of milliseconds before the request times out.

If the request takes longer than timeout milliseconds, then it is aborted.

The format for the axios.get() method is axios.get(URL, CONFIG_OBJECT).

However, when issuing a POST, PUT or PATCH request, the syntax is axios.get(URL, REQUEST_BODY, CONFIG_OBJECT).

Here is an example of setting the timeout property when issuing a POST request.

index.js
import axios from 'axios'; // ๐Ÿ‘‡๏ธ if you use CommonJS require() // const axios = require('axios'); async function createPost() { try { const response = await axios.post( 'https://jsonplaceholder.typicode.com/posts', { name: 'Bobby Hadz', post: 'Handle timeouts in Axios', }, { timeout: 3000, headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, }, ); return response.data; } catch (err) { if (err.code === 'ECONNABORTED') { console.log('The request timed out.'); } else { console.log(err); } } } createPost().then(result => { console.log(result); });

set timeout in axios post request

The code for this article is available on GitHub

Notice that the timeout property is set in the third parameter we passed to the axios.post() method.

The second parameter is the request body.

If 3 seconds pass and the API doesn't respond, then the request will be aborted and the if block in the catch() function will run.

index.js
catch (err) { if (err.code === 'ECONNABORTED') { console.log('The request timed out.'); } else { console.log(err); } }

If the request doesn't time out but a different error is raised, then the else block will run.

# Setting the timeout property for multiple requests

If you need to set the timeout property for multiple requests, create an axios instance.

index.js
import axios from 'axios'; // ๐Ÿ‘‡๏ธ if you use CommonJS require // const axios = require('axios'); export const placeholderApi = axios.create({ baseURL: 'https://jsonplaceholder.typicode.com', timeout: 3000, }); async function getPosts() { try { const response = await placeholderApi.get('/posts', { headers: { Accept: 'application/json', }, }); return response.data; } catch (err) { if (err.code === 'ECONNABORTED') { console.log('The request timed out.'); } else { console.log(err); } } } getPosts().then(result => { console.log(result); });
The code for this article is available on GitHub

We used the axios.create() method to create an axios instance and set the timeout property to 3000 milliseconds (3 seconds).

index.js
const placeholderApi = axios.create({ baseURL: 'https://jsonplaceholder.typicode.com', timeout: 3000, });

Notice that we called the instance.get() method and not axios.get().

index.js
const response = await placeholderApi.get('/posts', { headers: { Accept: 'application/json', }, });

We set the timeout property when creating the axios instance, so it applies to all requests that are issued using the instance.

We didn't have to set the timeout property in the configuration object because it is already set on the instance.

However, you could overwrite the timeout for a specific request by explicitly providing it.

index.js
const response = await placeholderApi.get('/posts', { timeout: 5000, headers: { Accept: 'application/json', }, });

Even though the example calls the instance.get() method that has a default timeout of 3 seconds, a timeout of 5 seconds will be applied because we explicitly overwrote the value.

Here is an example of issuing a POST request with the axios instance and the timeout of 3 seconds applied.

index.js
import axios from 'axios'; // ๐Ÿ‘‡๏ธ if you use CommonJS require // const axios = require('axios'); const placeholderApi = axios.create({ baseURL: 'https://jsonplaceholder.typicode.com', timeout: 3000, }); async function createPost() { try { const response = await placeholderApi.post( '/posts', { name: 'Bobby Hadz', post: 'Handle timeouts in Axios', }, { headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, }, ); return response.data; } catch (err) { if (err.code === 'ECONNABORTED') { console.log('The request timed out.'); } else { console.log(err); } } } createPost().then(result => { console.log(result); });

set timeout property for multiple requests

The code for this article is available on GitHub

Notice that we used the instance.post() method and not axios.post() when issuing the POST request.

index.js
// ๐Ÿ‘‡๏ธ using instance.post() const response = await placeholderApi.post( '/posts', { name: 'Bobby Hadz', post: 'Handle timeouts in Axios', }, { headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, }, );

I've also written a detailed guide on how to change the Base URL in axios.

# The axios timeout property is for response timeouts, not connection timeouts

The timeout property in axios works when responses time out, not when a connection times out.

In other words, if you make an HTTP request and the server takes longer than timeout milliseconds to respond, then the request will be aborted and the specified timeout will work.

However, if you have connectivity issues (e.g. lose internet connection), or the specified IP address or domain name is incorrect or unavailable, then the timeout property won't work.

In this case, you have to use one of the provided by axios cancellation methods.

Here is an example that uses the signal property with the AbortSignal.timeout() method.

index.js
import axios from 'axios'; // ๐Ÿ‘‡๏ธ if you use CommonJS require() // const axios = require('axios'); async function getPosts() { try { const response = await axios.get( 'https://jsonplaceholder.typicode.com/posts', { // ๐Ÿ‘‡๏ธ aborts request if response takes longer than 3 seconds timeout: 3000, // ๐Ÿ‘‡๏ธ aborts request after 3 seconds (connectivity issues) signal: AbortSignal.timeout(3000), headers: { Accept: 'application/json', }, }, ); return response.data; } catch (err) { if (err.code === 'ECONNABORTED') { console.log('The request timed out.'); } else { console.log(err); } } } getPosts().then(result => { console.log(result); });
The code for this article is available on GitHub

The AbortSignal.timeout() method returns an AbortSignal that will automatically abort after a specified time (3 seconds in the example).

This covers us in the scenario where there are connectivity issues and the timeout property covers us in the scenario where the server takes too long to respond.

The AbortSignal.timeout() method is built-in, however, you can also create your old custom AbortController signal.

index.js
import axios from 'axios'; // ๐Ÿ‘‡๏ธ if you use CommonJS require() // const axios = require('axios'); function newAbortSignal(timeoutMs) { const abortController = new AbortController(); setTimeout(() => abortController.abort(), timeoutMs || 0); return abortController.signal; } async function getPosts() { try { const response = await axios.get( 'https://jsonplaceholder.typicode.com/posts', { // ๐Ÿ‘‡๏ธ aborts request if response takes longer than 3 seconds timeout: 3000, // ๐Ÿ‘‡๏ธ aborts request after 3 seconds (connectivity issues) signal: newAbortSignal(3000), headers: { Accept: 'application/json', }, }, ); return response.data; } catch (err) { if (err.code === 'ECONNABORTED') { console.log('The request timed out.'); } else { console.log(err); } } } getPosts().then(result => { console.log(result); });
The code for this article is available on GitHub

We set the signal property to the result of calling the newAbortSignal() function with the desired timeout in milliseconds.

The AbortController() constructor creates a new AbortController object instance.

The AbortController object enables you to abort one or more HTTP requests.

index.js
function newAbortSignal(timeoutMs) { const abortController = new AbortController(); setTimeout(() => abortController.abort(), timeoutMs || 0); return abortController.signal; }

The AbortController.abort() method is used to abort DOM and fetch requests.

The AbortController.signal property returns an AbortSignal object instance that can be used to abort a DOM or fetch request.

I've also written an article on how to download files and images using axios.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev