Overview
The API client provides a set of functions for making HTTP requests to the backend API. It includes automatic authentication, error handling, timeout management, retry logic, and session management.Import
Configuration
The API base URL is configured via environment variable:VITE_API_URL is set in your .env file:
Core Function
request()
Low-level HTTP request function with automatic authentication, timeout, and retry capabilities.Parameters
API endpoint path (without base URL). Example:
"/auth/login" or "/users/123"Request configuration options:Standard RequestInit options:
method: HTTP method (GET, POST, etc.)headers: Additional headersbody: Request body (will be sent with Content-Type: application/json)
retry(number): Number of retry attempts on failure. Default:0timeOut(number): Request timeout in milliseconds. Default:30000(30 seconds)
Returns
Returns a Promise that resolves to:- Parsed JSON response for successful requests
nullfor 204 No Content responses- Throws an error for failed requests
Behavior
Authentication:- Automatically includes credentials (cookies) with
credentials: "include" - On 401 Unauthorized, automatically calls
useAuthStore.getState().logout()
- Automatically sets
Content-Type: application/jsonwhen a body is present - Merges custom headers from options
- Uses AbortController to cancel requests that exceed the timeout
- Throws “Request timeout” error if timeout is reached
- Extracts error message from response JSON when available
- Falls back to generic “API request failed” message
- Preserves error types for proper error handling
- Automatically retries failed requests up to
retrycount - Does NOT retry on 401 (Unauthorized) or 403 (Forbidden)
- Does NOT retry on timeout errors
Example
Convenience Methods
apiGET()
Make a GET request to the API.API endpoint path
Optional request configuration (merged with
method: "GET")apiPOST()
Make a POST request to the API.API endpoint path
Request configuration (merged with
method: "POST"). Typically includes body property.apiPATCH()
Make a PATCH request to the API.API endpoint path
Request configuration (merged with
method: "PATCH"). Typically includes body property.apiDELETE()
Make a DELETE request to the API.API endpoint path
Optional request configuration (merged with
method: "DELETE")Error Handling
The API client throws errors in the following scenarios:Unauthorized (401)
Request Timeout
API Errors
Best Practices
Advanced Usage
Custom Headers
Retry Configuration
Custom Timeout
File Upload
Source
Implemented in:src/app/api/client.ts:5