How to Simulate Slow Network in Axios
Simulating slow network connections in Axios is essential for testing user interface loading states, request timeouts, and race conditions during frontend development. This article outlines the most effective techniques to introduce artificial network latency directly within your Axios configuration, covering Axios interceptors, mock libraries, and browser-level throttling.
1. Using Axios Interceptors
The most direct way to introduce latency in your codebase without third-party libraries is by using an Axios response or request interceptor. By returning a Promise that resolves after a specified timeout, you force Axios to wait before delivering the response.
import axios from 'axios';
const api = axios.create({
baseURL: 'https://api.example.com',
});
// Helper function to delay execution
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// Add response interceptor
api.interceptors.response.use(
async (response) => {
if (process.env.NODE_ENV === 'development') {
await delay(2000); // Simulate a 2-second network latency
}
return response;
},
async (error) => {
if (process.env.NODE_ENV === 'development') {
await delay(2000);
}
return Promise.reject(error);
}
);
export default api;2. Using
axios-mock-adapter
If your project uses axios-mock-adapter for unit testing
or API mocking, you can use its built-in delayResponse
configuration option to simulate slow connections globally or per
request.
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
const api = axios.create();
// Create mock adapter with a global delay of 1500ms
const mock = new MockAdapter(api, { delayResponse: 1500 });
// Mock an endpoint
mock.onGet('/users').reply(200, [
{ id: 1, name: 'John Doe' },
]);
api.get('/users').then((response) => {
console.log(response.data); // Received after 1.5 seconds
});3. Using a Custom Adapter Wrapper
You can wrap Axios's default adapter to add artificial latency before the request executes or before the response is resolved. This method works well if you want complete control over the underlying transport layer.
import axios from 'axios';
const defaultAdapter = axios.defaults.adapter;
const slowAdapter = async (config) => {
await new Promise((resolve) => setTimeout(resolve, 3000)); // 3-second delay
return defaultAdapter(config);
};
const api = axios.create({
adapter: process.env.NODE_ENV === 'development' ? slowAdapter : defaultAdapter,
});4. Browser DevTools Throttling (Alternative)
If you prefer not to modify your application code, you can simulate slow network profiles using browser developer tools:
- Open your browser's Developer Tools (
F12orCtrl + Shift + I). - Navigate to the Network tab.
- Locate the Throttling dropdown (typically labeled No throttling or Online).
- Select Slow 3G, Fast 3G, or define a Custom profile with specific latency and bandwidth limits.