Last updated: Apr 4, 2024
Reading timeยท5 min
Make sure you have axios
installed to be able to run the code samples.
npm init -y # install using NPM npm install axios # or install using YARN yarn add axios
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.
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); });
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)
.
axios.get(URL, REQUEST_BODY, CONFIG_OBJECT)
.Here is an example of setting the timeout
property when issuing a POST
request.
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); });
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.
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.
timeout
property for multiple requestsIf you need to set the timeout
property for multiple requests, create an
axios
instance.
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); });
We used the
axios.create() method to
create an axios
instance and set the timeout
property to 3000 milliseconds
(3 seconds).
const placeholderApi = axios.create({ baseURL: 'https://jsonplaceholder.typicode.com', timeout: 3000, });
Notice that we called the instance.get()
method and not axios.get()
.
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.
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.
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); });
Notice that we used the instance.post()
method and not axios.post()
when
issuing the POST request.
// ๐๏ธ 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
.
axios
timeout property is for response timeouts, not connection timeoutsThe 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.
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
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.
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); });
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.
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.
You can learn more about the related topics by checking out the following tutorials: