Axios Setup
14.1.1. Axios Instance Creation
- The API client must create a dedicated instance using
axios.create(). - The global
axiosobject must not be used directly. This prevents pollution of global settings. - The instance definition file must be located at
src/api/client.ts. - When a single project must communicate with multiple API servers, separate instances must be created for each server.
typescript
// src/api/client.ts
import axios from 'axios'
import type { AxiosInstance } from 'axios'
const apiClient: AxiosInstance = axios.create({
baseURL: import.meta.env.VITE_API_BASE_URL,
timeout: 30000,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
})
export default apiClient14.1.2. Environment-Specific baseURL Configuration
baseURLmust not be hardcoded. It must be injected through environment variables.- Following Vite environment variable conventions, the
VITE_prefix must be used. - Environment-specific
.envfiles must be maintained separately.
| File | Purpose | Example Value |
|---|---|---|
.env.development | Local development | http://localhost:8080/api |
.env.staging | Staging deployment | https://staging-api.example.com |
.env.production | Production deployment | https://api.example.com |
- Access via
import.meta.env.VITE_API_BASE_URL, and declare the type inenv.d.tsfor type safety.
typescript
// src/env.d.ts
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_API_BASE_URL: string
}
interface ImportMeta {
readonly env: ImportMetaEnv
}14.1.3. Default Headers
Content-Typemust be set toapplication/jsonby default.- The
Acceptheader must be set toapplication/jsonby default. - Requests that require a different
Content-Type, such as file uploads, must override it on a per-request basis.
typescript
// Example: Overriding Content-Type for file uploads
await apiClient.post('/files/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
})- When custom headers are required, they must be injected dynamically through interceptors. Only static values should be set at instance creation time.
14.1.4. Timeout Configuration
- The default timeout must be set to 30,000ms (30 seconds).
- Long-running requests must override the timeout in the per-request options.
- Timeout values must be managed as constants.
typescript
// src/api/constants.ts
export const API_TIMEOUT = {
DEFAULT: 30000,
UPLOAD: 120000,
REPORT: 60000,
} as consttypescript
// Overriding timeout for large file uploads
await apiClient.post('/files/upload', formData, {
timeout: API_TIMEOUT.UPLOAD,
headers: {
'Content-Type': 'multipart/form-data',
},
})| Request Type | Timeout | Notes |
|---|---|---|
| General API requests | 30,000ms | Default |
| File uploads | 120,000ms | Per-request override |
| Report generation | 60,000ms | Per-request override |
- When a timeout occurs, the
codeproperty ofAxiosErroris set toECONNABORTED. An appropriate notification message must be displayed to the user based on this value.