5.8 KiB
5.8 KiB
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
-
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
-
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
-
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
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
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:
- Client-side Remix ENV injection (
window.ENV.VITE_*) - Vite import.meta.env (build-time injection)
- Node.js process.env (server-side)
- Environment-based fallbacks
- Static fallbacks (development defaults)
📝 Usage Examples
Using API Client Factory (Recommended)
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
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
import { isProduction, isDevelopment } from "~/utils/api-config";
if (isProduction()) {
// Production-specific logic
}
🚀 Benefits
DevOps Advantages
- Environment Parity: Same codebase works across all environments
- Configuration as Code: All API endpoints defined in environment variables
- Zero Hardcoded Values: No more environment-specific builds
- Deployment Flexibility: Easy to switch between staging/prod domains
- Container-Ready: Perfect for Docker and Kubernetes deployments
Development Benefits
- Type Safety: Full TypeScript support with proper fallbacks
- Centralized Management: Single source of truth for all API configuration
- Consistent Auth: Automatic bearer token injection
- Error Resilience: Graceful fallbacks prevent runtime failures
🔧 Migration Guide
Updating Existing Hooks
Before:
const basePath = import.meta.env.VITE_API_BASE_URL;
const config = new Configuration({
basePath,
headers: { /* ... */ }
});
const api = new UserManagementApi(config);
After:
import { createUserManagementApi } from "~/utils/api-client-factory";
const api = createUserManagementApi(token);
Updating WebSocket Connections
Before:
const baseSocketPath = import.meta.env.VITE_API_SOCKET_BASE_URL;
After:
import { getSocketBaseUrl } from "~/utils/api-config";
const baseSocketPath = getSocketBaseUrl();
🧪 Testing Configuration
Local Development
# Test development configuration
npm run dev
# Test production configuration locally
NODE_ENV=production npm run build
npm run start
Environment Variables Testing
# Override for testing
VITE_API_BASE_URL=https://api.staging.vitrown.com npm run dev
🔒 Security Considerations
- No Secrets in Config: Only public endpoints are configured
- Runtime Token Injection: Authentication tokens added at request time
- Fallback Safety: Default fallbacks prevent exposure of internal services
- Type Safety: Prevents configuration errors at compile time
📊 Monitoring & Debugging
Environment Verification
import { getApiConfig } from "~/utils/api-config";
console.log("Current API Configuration:", getApiConfig());
Build-time Verification
Check your build output for correct environment variable injection:
npm run build
# Verify the built files contain correct API endpoints
🚨 Troubleshooting
Common Issues
-
Undefined Environment Variables
- Ensure
.env.productionhas all required variables - Check Vite prefix requirements (
VITE_prefix)
- Ensure
-
Server-Side vs Client-Side
- Use
window.ENVfor Remix server-injected variables - Use
import.meta.envfor Vite build-time injection
- Use
-
Docker/Container Issues
- Ensure environment variables are passed to container
- Use
docker-compose.ymlenvironment section
Debug Commands
# 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