Vitron-Front/docs/API_CONFIGURATION.md
2026-04-29 01:44:16 +03:30

210 lines
5.8 KiB
Markdown

# API Configuration Guide
## Overview
This document outlines the robust, environment-aware API configuration system implemented for the Vitron frontend application. The system eliminates hardcoded API endpoints and provides dynamic configuration based on environment variables.
## Architecture
### 🏗️ Core Components
1. **Dynamic BASE_PATH** (`src/api/types/runtime.ts`)
- Auto-generated API types now use environment-aware BASE_PATH
- Supports both client-side and server-side environments
- Graceful fallbacks for different deployment scenarios
2. **Centralized API Config** (`app/utils/api-config.ts`)
- Utility functions for all API endpoints (HTTP, WebSocket, Site URLs)
- Environment detection and fallback logic
- Type-safe configuration management
3. **API Client Factory** (`app/utils/api-client-factory.ts`)
- Centralized factory for creating configured API clients
- Consistent authentication header management
- Single source of truth for API configuration
## 🌍 Environment Configuration
### Development Environment
```env
VITE_API_BASE_URL=https://api.dev.vitrown.com
VITE_API_SOCKET_BASE_URL=wss://api.dev.vitrown.com
VITE_SITE_URL=https://dev.vitrown.com
VITE_DOMAIN_URL=https://dev.vitrown.com
```
### Production Environment
```env
VITE_API_BASE_URL=https://api.prod.vitrown.com
VITE_API_SOCKET_BASE_URL=wss://api.prod.vitrown.com
VITE_SITE_URL=https://vitrown.com
VITE_DOMAIN_URL=https://vitrown.com
```
## 🔄 Configuration Resolution Order
The system follows this priority order for configuration resolution:
1. **Client-side Remix ENV injection** (`window.ENV.VITE_*`)
2. **Vite import.meta.env** (build-time injection)
3. **Node.js process.env** (server-side)
4. **Environment-based fallbacks**
5. **Static fallbacks** (development defaults)
## 📝 Usage Examples
### Using API Client Factory (Recommended)
```typescript
import { createUserManagementApi } from "~/utils/api-client-factory";
// In your hook or component
const userApi = createUserManagementApi(token);
const response = await userApi.userManagementSendOtpPost({
phoneNumber: "1234567890"
});
```
### Using Centralized Config
```typescript
import { getApiBaseUrl, getSocketBaseUrl } from "~/utils/api-config";
// For WebSocket connections
const wsUrl = `${getSocketBaseUrl()}/ws/chat/${threadId}/?token=${token}`;
// For manual fetch calls
const response = await fetch(`${getApiBaseUrl()}/api/custom-endpoint`);
```
### Environment Detection
```typescript
import { isProduction, isDevelopment } from "~/utils/api-config";
if (isProduction()) {
// Production-specific logic
}
```
## 🚀 Benefits
### DevOps Advantages
1. **Environment Parity**: Same codebase works across all environments
2. **Configuration as Code**: All API endpoints defined in environment variables
3. **Zero Hardcoded Values**: No more environment-specific builds
4. **Deployment Flexibility**: Easy to switch between staging/prod domains
5. **Container-Ready**: Perfect for Docker and Kubernetes deployments
### Development Benefits
1. **Type Safety**: Full TypeScript support with proper fallbacks
2. **Centralized Management**: Single source of truth for all API configuration
3. **Consistent Auth**: Automatic bearer token injection
4. **Error Resilience**: Graceful fallbacks prevent runtime failures
## 🔧 Migration Guide
### Updating Existing Hooks
**Before:**
```typescript
const basePath = import.meta.env.VITE_API_BASE_URL;
const config = new Configuration({
basePath,
headers: { /* ... */ }
});
const api = new UserManagementApi(config);
```
**After:**
```typescript
import { createUserManagementApi } from "~/utils/api-client-factory";
const api = createUserManagementApi(token);
```
### Updating WebSocket Connections
**Before:**
```typescript
const baseSocketPath = import.meta.env.VITE_API_SOCKET_BASE_URL;
```
**After:**
```typescript
import { getSocketBaseUrl } from "~/utils/api-config";
const baseSocketPath = getSocketBaseUrl();
```
## 🧪 Testing Configuration
### Local Development
```bash
# Test development configuration
npm run dev
# Test production configuration locally
NODE_ENV=production npm run build
npm run start
```
### Environment Variables Testing
```bash
# Override for testing
VITE_API_BASE_URL=https://api.staging.vitrown.com npm run dev
```
## 🔒 Security Considerations
1. **No Secrets in Config**: Only public endpoints are configured
2. **Runtime Token Injection**: Authentication tokens added at request time
3. **Fallback Safety**: Default fallbacks prevent exposure of internal services
4. **Type Safety**: Prevents configuration errors at compile time
## 📊 Monitoring & Debugging
### Environment Verification
```typescript
import { getApiConfig } from "~/utils/api-config";
console.log("Current API Configuration:", getApiConfig());
```
### Build-time Verification
Check your build output for correct environment variable injection:
```bash
npm run build
# Verify the built files contain correct API endpoints
```
## 🚨 Troubleshooting
### Common Issues
1. **Undefined Environment Variables**
- Ensure `.env.production` has all required variables
- Check Vite prefix requirements (`VITE_` prefix)
2. **Server-Side vs Client-Side**
- Use `window.ENV` for Remix server-injected variables
- Use `import.meta.env` for Vite build-time injection
3. **Docker/Container Issues**
- Ensure environment variables are passed to container
- Use `docker-compose.yml` environment section
### Debug Commands
```bash
# Check current environment
npm run generate:types # Regenerate API types
npm run typecheck # Verify TypeScript compilation
npm run build # Test production build
```
## 🎯 Future Enhancements
- [ ] Runtime configuration refresh (for long-running apps)
- [ ] Configuration validation middleware
- [ ] Health check endpoints for configuration verification
- [ ] Automated environment variable documentation generation