How to Handle Timeouts in Axios
When making HTTP requests, your application can't wait forever for a response. A slow or unresponsive server can cause your application to hang, leading to a poor user experience. Setting a timeout is a critical part of building resilient applications, as it allows you to abort a request that is taking too long.
This guide will teach you the modern, standard method for setting timeouts in Axios. You will learn the crucial difference between a response timeout and a connection timeout, and how to handle both correctly.
The Core Concept: Response vs. Connection Timeouts
It's essential to understand that there are two main reasons a request might "time out":
- Response Timeout: The connection to the server was successful, but the server is taking too long to process the request and send back a response. This is the most common scenario.
- Connection Timeout: A connection to the server could not be established in the first place. This can happen due to network issues, DNS problems, or the server being down.
Axios's built-in timeout option only handles the first scenario. For the second, we need a different tool.
Method 1 (Recommended): Setting a Response Timeout
The timeout property in the Axios config specifies the number of milliseconds to wait for a server response before aborting the request.
The Best Practice is to create an Axios Instance.
- For most applications, the best practice is to create a dedicated Axios instance with a default timeout. This keeps your configuration centralized and your code clean.
For example, we want to ensure our API calls don't hang for more than 5 seconds.
Solution:
import axios from 'axios';
// Create an instance with a default timeout of 5000ms (5 seconds)
const api = axios.create({
baseURL: 'https://api.example.com',
timeout: 5000,
});
async function getPosts() {
try {
// All requests made with this instance will now have a 5-second timeout.
const response = await api.get('/posts');
return response.data;
} catch (error) {
// The error handling for timeouts is explained in a later section
console.error('Request failed:', error.message);
}
}
You can also override this default for a specific request:
// This specific request will wait up to 10 seconds.
const response = await api.get('/very-slow-endpoint', { timeout: 10000 });
Method 2 (Advanced): Setting a Connection Timeout
The timeout property does not apply to the initial connection. If the server is unreachable, the request may hang for a much longer, system-dependent time (e.g., 20+ seconds). To control this, we must use an AbortSignal.
Logic: The AbortSignal.timeout() static method (available in modern browsers and Node.js v17.3.0+) creates a signal that will automatically abort a request after a specified time.
Solution: you can provide both a timeout and a signal for the most robust protection.
import axios from 'axios';
async function getPosts() {
try {
const response = await axios.get('https://non-existent-server.example.com/posts', {
// For a slow server response
timeout: 5000,
// For a failed initial connection
signal: AbortSignal.timeout(5000),
});
return response.data;
} catch (error) {
console.error('Request failed:', error.message);
}
}
This configuration ensures that the request will be aborted after 5 seconds, whether the failure is due to a slow response or an unreachable server.
Robust Error Handling for Timeouts
When a request is aborted due to a timeout, Axios throws a specific type of error. You can check for this to provide a clear error message to the user.
This try...catch block shows how to identify a timeout error.
async function makeRequest() {
try {
const response = await axios.get('https://example.com/delay/5', {
timeout: 2000,
});
return response.data;
} catch (error) {
// The `timeout` property error code is 'ECONNABORTED'
if (error.code === 'ECONNABORTED') {
console.log('Request timed out because the server took too long to respond.');
}
// The `signal` property error name is 'CanceledError'
else if (axios.isCancel(error)) {
console.log('Request timed out due to a connection issue.');
}
else {
// Handle other errors (e.g., 404, 500)
console.error('An unexpected error occurred:', error.message);
}
}
}
Conclusion
Handling timeouts is a critical part of building resilient applications with Axios.
- The
timeoutproperty is the standard way to handle slow server responses. The best practice is to set a default value when you create an Axios instance withaxios.create(). - For robust protection against unreachable servers or network issues, you should also provide an
AbortSignal.timeout()in your request configuration. - Always include a
try...catchblock to gracefully handle timeout errors by checking forerror.code === 'ECONNABORTED'oraxios.isCancel(error).