How to Configure Timeouts in Axios
Configuring timeout thresholds for outgoing requests in the Axios HTTP client ensures that your application does not hang indefinitely when a server is unresponsive. This article explains how to define timeouts globally, within custom Axios instances, and on individual requests, as well as how to properly catch and handle timeout-related errors in your code.
Understanding the Timeout Property
In Axios, the timeout property specifies the number of
milliseconds before the request is aborted. If the request takes longer
than the defined value, Axios will automatically cancel the operation
and throw an error. The default value is 0, meaning no
timeout is applied.
Setting Timeouts on a Single Request
To set a timeout for a specific request, pass the
timeout option inside the request configuration object.
const axios = require('axios');
axios.get('https://api.example.com/data', {
timeout: 5000 // Timeout after 5 seconds
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});Setting Timeouts on a Custom Axios Instance
When building scalable applications, it is standard practice to create a dedicated Axios instance with pre-configured settings, including a base URL and a timeout threshold.
const axios = require('axios');
const apiClient = axios.create({
baseURL: 'https://api.example.com',
timeout: 10000 // 10-second timeout for all requests via this instance
});
// Uses the 10-second timeout configured above
apiClient.get('/users')
.then(response => console.log(response.data))
.catch(error => console.error(error));You can still override the instance timeout on specific calls by
providing a new timeout value in that specific request's
config.
Setting Global Timeout Defaults
If you want to apply a timeout to all standard Axios requests across your entire application, configure the global default:
const axios = require('axios');
axios.defaults.timeout = 8000; // 8-second global timeoutHandling Timeout Errors
When a request exceeds the configured threshold, Axios terminates the
connection and returns an error with the code ECONNABORTED.
You can inspect this code to handle timeouts specifically:
axios.get('https://api.example.com/data', { timeout: 3000 })
.then(response => {
console.log(response.data);
})
.catch(error => {
if (error.code === 'ECONNABORTED') {
console.error('Request timed out. Please try again.');
} else {
console.error('An unexpected error occurred:', error.message);
}
});