Files
main/rules-mdc/axios.mdc
T
sanjeed5 5cbc31aee9 Update generation system with modern prompts and Gemini 2.5 Flash
- Upgrade to gemini-2.5-flash model for better output quality
- Add date context to prompts (December 2025) for current best practices
- Implement Exa cache system to avoid redundant API calls
- Add --refresh-exa flag to bypass cache when needed
- Restructure prompts with date at end for Gemini prompt caching
- Enhance system prompt to emphasize modern patterns
- Switch from JSON mode to direct MDC format generation
- Add loguru dependency for better logging
- Remove requirements.txt in favor of uv
2025-12-17 21:12:15 +05:30

227 lines
11 KiB
Plaintext

---
description: Comprehensive best practices for using the Axios HTTP client library, covering code organization, common patterns, performance, pitfalls, and testing.
globs: **/*.{js,jsx,ts,tsx}
---
# Axios Best Practices
Axios is a powerful, promise-based HTTP client for browsers and Node.js. Adhering to best practices ensures maintainable, performant, and robust API interactions in your applications.
## 1. Code Organization and Structure
- **Centralize Configuration with Axios Instances:** Always create dedicated Axios instances using `axios.create()` to centralize common configurations like `baseURL`, `timeout`, and default `headers`. This reduces boilerplate and ensures consistency across your application.
javascript
// api.js or http-client.js
import axios from 'axios';
export const apiClient = axios.create({
baseURL: import.meta.env.VITE_API_URL || 'http://localhost:3000/api',
timeout: 8000, // Request timeout in milliseconds
headers: {
'Content-Type': 'application/json',
},
});
- **Dedicated API Modules/Services:** Organize your API calls into separate modules or service files, following the Single Responsibility Principle. Each module should handle requests for a specific resource or feature.
javascript
// services/userService.js
import { apiClient } from '../api';
export const userService = {
getAllUsers: () => apiClient.get('/users'),
getUserById: (id) => apiClient.get(`/users/${id}`),
createUser: (userData) => apiClient.post('/users', userData),
updateUser: (id, userData) => apiClient.put(`/users/${id}`, userData),
deleteUser: (id) => apiClient.delete(`/users/${id}`),
};
// In a component or business logic:
// import { userService } from '../services/userService';
// const users = await userService.getAllUsers();
- **Leverage Interceptors for Global Logic:** Use request and response interceptors to centralize cross-cutting concerns like authentication, logging, error handling, and data transformation.
javascript
// In api.js or http-client.js, after creating apiClient
// Request Interceptor: Add authentication token
apiClient.interceptors.request.use(
(config) => {
const token = localStorage.getItem('jwt');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
// Log outgoing request (optional)
console.log(`[Axios] ${config.method.toUpperCase()} ${config.url}`);
return config;
},
(error) => {
return Promise.reject(error);
}
);
// Response Interceptor: Unified error handling and response transformation
apiClient.interceptors.response.use(
(response) => {
// You can transform response data here if needed
return response;
},
(error) => {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.error('[Axios Error] Status:', error.response.status, 'Data:', error.response.data);
if (error.response.status === 401) {
// Handle unauthorized errors, e.g., redirect to login
console.error('Unauthorized: Redirecting to login...');
// window.location.href = '/login';
}
// You can throw a custom error here for more specific handling in components
return Promise.reject(new Error(error.response.data.message || 'An API error occurred.'));
} else if (error.request) {
// The request was made but no response was received
console.error('[Axios Error] No response received:', error.request);
return Promise.reject(new Error('No response from server. Please check your network connection.'));
} else {
// Something happened in setting up the request that triggered an Error
console.error('[Axios Error] Request setup error:', error.message);
return Promise.reject(new Error('An unexpected error occurred.'));
}
}
);
## 2. Common Patterns and Anti-patterns
- **Pattern: Use `async/await`:** Prefer `async/await` for cleaner, more readable asynchronous code over `.then().catch()` chains, especially when dealing with multiple sequential requests or complex logic.
javascript
// Good: Using async/await
async function fetchUserData(userId) {
try {
const response = await apiClient.get(`/users/${userId}`);
return response.data;
} catch (error) {
console.error('Failed to fetch user data:', error.message);
throw error; // Re-throw to allow further handling
}
}
- **Pattern: Request Cancellation with `AbortController`:** For long-running requests or when a component might unmount before a request completes, use `AbortController` to cancel requests. This prevents memory leaks and unnecessary network activity.
javascript
// In a React component's useEffect or similar lifecycle hook
useEffect(() => {
const controller = new AbortController();
const signal = controller.signal;
async function fetchData() {
try {
const response = await apiClient.get('/data', { signal });
console.log(response.data);
} catch (error) {
if (axios.isCancel(error)) {
console.log('Request cancelled:', error.message);
} else {
console.error('Error fetching data:', error.message);
}
}
}
fetchData();
return () => {
// Abort the request if the component unmounts
controller.abort();
};
}, []);
- **Anti-pattern: Direct `axios` calls everywhere:** Avoid `import axios from 'axios';` and then calling `axios.get()` directly in multiple places without using a configured instance. This leads to scattered configuration and makes global changes difficult.
- **Anti-pattern: Ignoring errors:** Always include `catch` blocks or implement comprehensive error handling via response interceptors. Unhandled promise rejections can lead to silent failures or crashes.
- **Anti-pattern: Hardcoding sensitive information:** Never hardcode `baseURL`, API keys, or other sensitive credentials directly in your code. Use environment variables (e.g., `process.env.VITE_API_URL` for Vite, `process.env.REACT_APP_API_URL` for Create React App, or `.env` files for Node.js).
## 3. Performance Considerations
- **Set Request Timeouts:** Always configure a `timeout` on your Axios instances or individual requests. This prevents requests from hanging indefinitely, especially in cases of network issues or unresponsive servers.
javascript
const apiClient = axios.create({
timeout: 10000, // 10 seconds
});
- **Combine `timeout` with `AbortSignal`:** Understand that `timeout` handles the time until a response is received, while `AbortSignal` allows for explicit cancellation of the underlying connection. For robust control, use both.
javascript
axios.get('/long-request', {
timeout: 5000, // Response timeout
signal: AbortSignal.timeout(10000) // Connection timeout after 10 seconds (Node.js 17.3+)
});
- **Client-Side Caching:** For frequently accessed data that doesn't change often, consider implementing client-side caching strategies (e.g., using libraries like `React Query`, `SWR`, or a custom in-memory cache). This reduces redundant network requests and improves perceived performance.
- **Request Throttling/Debouncing:** For user interactions that trigger frequent API calls (e.g., search input, scroll events), implement throttling or debouncing to limit the rate of requests sent to the server. This prevents overloading the backend and improves client-side responsiveness.
- **Minimize Bundle Size (Contextual):** While Axios is generally lightweight, for extremely small applications where every byte counts, the native `Fetch API` might be considered. However, Axios's features (interceptors, automatic JSON parsing, error handling) often justify its inclusion for most projects.
## 4. Common Pitfalls and Gotchas
- **Forgetting to Return in Interceptors:** Request and response interceptors *must* return the `config` or `response` object, respectively, or a `Promise.reject(error)` for error handlers. Failing to do so will halt the request/response chain.
- **`cancelToken` is Deprecated:** Avoid using `axios.CancelToken`. The modern and recommended approach for request cancellation is `AbortController`.
- **Misunderstanding `timeout` vs. `AbortSignal`:** As mentioned, `timeout` is for response time, `AbortSignal` is for connection cancellation. Use both for comprehensive control.
- **CORS Issues:** Cross-Origin Resource Sharing (CORS) errors are common when the frontend and backend are on different domains. While primarily a backend configuration issue, ensure your frontend sends necessary headers (e.g., `Authorization`) that the backend expects for CORS preflight requests.
- **Incorrect `Content-Type` for `POST`/`PUT`:** Axios automatically sets `Content-Type: application/json` for plain JavaScript objects. However, for other data types (e.g., `FormData` for file uploads), ensure you explicitly set the correct `Content-Type` header if Axios doesn't handle it automatically.
- **Handling Different Error Structures:** APIs can return errors in various formats. Your response interceptor should be robust enough to parse different error structures (e.g., `error.response.data.message`, `error.response.data.errors`).
## 5. Testing Approaches
- **Mocking API Responses:** For unit and integration tests, avoid making actual network requests. Use mocking libraries to simulate API responses.
- **`axios-mock-adapter`:** A popular library specifically designed for mocking Axios requests. It allows you to define expected requests and return mock responses.
javascript
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import { userService } from '../services/userService'; // Your API service
const mock = new MockAdapter(axios); // Or new MockAdapter(apiClient);
describe('User Service', () => {
afterEach(() => {
mock.reset(); // Reset mocks after each test
});
test('should fetch all users', async () => {
const mockUsers = [{ id: 1, name: 'Alice' }];
mock.onGet('/users').reply(200, mockUsers);
const users = await userService.getAllUsers();
expect(users.data).toEqual(mockUsers);
});
test('should handle fetch error', async () => {
mock.onGet('/users').reply(500, { message: 'Server Error' });
await expect(userService.getAllUsers()).rejects.toThrow('An API error occurred.');
});
});
- **`MSW (Mock Service Worker)`:** A more powerful alternative that intercepts network requests at the service worker level (browser) or Node.js level. This allows for realistic mocking that works across different HTTP clients (Axios, Fetch, etc.) and is great for end-to-end testing scenarios.
- **Unit Test API Service Functions:** Write tests for your individual API service functions to ensure they construct the correct URLs, methods, and data payloads.
- **Test Interceptors:** Ensure your request and response interceptors behave as expected, e.g., that authentication tokens are added, and error responses are handled gracefully.