Skip to main content

Overview

VoicePact uses environment variables to manage configuration across development, testing, and production environments. The backend (FastAPI) and client (Next.js) each have their own configuration requirements.

Backend Environment Configuration

The backend uses pydantic-settings for type-safe environment variable management with validation.

Creating the Environment File

  1. Navigate to the server directory:
cd server
  1. Create a .env file (copy from .env.example if available):
touch .env

Required Backend Variables

Application Settings

# Application Identity
APP_NAME=VoicePact
APP_VERSION=1.0.0
ENVIRONMENT=development  # Options: development, testing, production
DEBUG=true
API_V1_PREFIX=/api/v1

Security Configuration

Generate strong, unique keys for production. Never commit these to version control.
# Security Keys (REQUIRED)
SECRET_KEY=your_secret_key_here_min_32_chars
SIGNATURE_PRIVATE_KEY=your_ed25519_private_key_64_chars
PASSWORD_SALT=your_password_salt_32_chars
WEBHOOK_SECRET=your_webhook_secret_32_chars

# Token Expiration
ACCESS_TOKEN_EXPIRE_MINUTES=10080  # 7 days
Generating Secure Keys:
import secrets

# Generate SECRET_KEY
print(f"SECRET_KEY={secrets.token_urlsafe(32)}")

# Generate SIGNATURE_PRIVATE_KEY
print(f"SIGNATURE_PRIVATE_KEY={secrets.token_urlsafe(64)}")

# Generate PASSWORD_SALT
print(f"PASSWORD_SALT={secrets.token_urlsafe(32)}")

# Generate WEBHOOK_SECRET
print(f"WEBHOOK_SECRET={secrets.token_urlsafe(32)}")

Africa’s Talking API

Sign up for an Africa’s Talking account at africastalking.com to get your credentials.
# Africa's Talking Configuration (REQUIRED)
AT_USERNAME=sandbox
AT_API_KEY=your_africastalking_api_key
AT_VOICE_NUMBER=+254XXXXXXXXX
AT_PAYMENT_PRODUCT_NAME=VoicePact
AT_USSD_SERVICE_CODE=*483#
For Production:
  • Use your production Africa’s Talking username (not sandbox)
  • Update AT_VOICE_NUMBER to your provisioned voice number
  • Ensure AT_PAYMENT_PRODUCT_NAME matches your registered product

Database Configuration

# SQLite (Development)
DATABASE_URL=sqlite:///./voicepact.db
DATABASE_ECHO=false  # Set to true for SQL query logging

# PostgreSQL (Production - Recommended)
# DATABASE_URL=postgresql+asyncpg://user:password@localhost:5432/voicepact
SQLite is suitable for development and small-scale deployments. For production, PostgreSQL is recommended for better concurrency and performance.

Redis Configuration

# Redis for Caching and Sessions (REQUIRED)
REDIS_URL=redis://localhost:6379/0
REDIS_MAX_CONNECTIONS=20
REDIS_SOCKET_TIMEOUT=30
Redis Cloud/Production Example:
REDIS_URL=redis://username:password@redis-host:6379/0

Voice Processing

# Whisper Model Configuration
WHISPER_MODEL_SIZE=small  # Options: tiny, base, small, medium, large
MAX_AUDIO_DURATION=1200  # 20 minutes in seconds
MAX_AUDIO_FILE_SIZE=52428800  # 50MB in bytes
SUPPORTED_AUDIO_FORMATS=wav,mp3,m4a,ogg,flac
Larger Whisper models provide better transcription accuracy but require more memory and processing time. small is a good balance for most use cases.

Webhook Configuration

# Webhook Base URL (REQUIRED for callbacks)
WEBHOOK_BASE_URL=https://your-domain.com

# For local development with ngrok:
# WEBHOOK_BASE_URL=https://your-ngrok-url.ngrok.io

CORS Configuration

# CORS Settings
CORS_ORIGINS=http://localhost:3000,http://127.0.0.1:3000
CORS_CREDENTIALS=true
CORS_METHODS=GET,POST,PUT,DELETE,OPTIONS
CORS_HEADERS=*
Production Example:
CORS_ORIGINS=https://app.voicepact.com,https://voicepact.com

Performance & Caching

# Performance Configuration
CACHE_TTL=3600  # 1 hour in seconds
MAX_WORKERS=4
REQUEST_TIMEOUT=30
HTTP_TIMEOUT=30
HTTP_MAX_CONNECTIONS=100
HTTP_MAX_KEEPALIVE=20

Logging

# Logging Configuration
LOG_LEVEL=INFO  # Options: DEBUG, INFO, WARNING, ERROR, CRITICAL
LOG_FORMAT=%(asctime)s - %(name)s - %(levelname)s - %(message)s
LOG_FILE=  # Leave empty for console only, or specify: /var/log/voicepact.log

Contract & Payment Settings

# Contract Configuration
CONTRACT_HASH_ALGORITHM=blake2b  # Options: blake2b, sha256
CONTRACT_SIGNATURE_ALGORITHM=ed25519  # Options: ed25519, rsa
MAX_CONTRACT_DURATION=31536000  # 1 year in seconds
CONTRACT_CONFIRMATION_TIMEOUT=86400  # 24 hours in seconds

# Payment Configuration
ESCROW_TIMEOUT=604800  # 7 days in seconds
PAYMENT_RETRY_ATTEMPTS=3
PAYMENT_RETRY_DELAY=300  # 5 minutes in seconds
MIN_PAYMENT_AMOUNT=100  # In cents (1 KES)
MAX_PAYMENT_AMOUNT=1000000  # In cents (10,000 KES)

Complete Backend .env Example

# Application
APP_NAME=VoicePact
APP_VERSION=1.0.0
ENVIRONMENT=development
DEBUG=true
API_V1_PREFIX=/api/v1

# Security
SECRET_KEY=generated_secret_key_here
SIGNATURE_PRIVATE_KEY=generated_signature_key_here
PASSWORD_SALT=generated_salt_here
WEBHOOK_SECRET=generated_webhook_secret_here
ACCESS_TOKEN_EXPIRE_MINUTES=10080

# Africa's Talking
AT_USERNAME=sandbox
AT_API_KEY=your_api_key_here
AT_VOICE_NUMBER=+254712345678
AT_PAYMENT_PRODUCT_NAME=VoicePact
AT_USSD_SERVICE_CODE=*483#

# Database
DATABASE_URL=sqlite:///./voicepact.db
DATABASE_ECHO=false

# Redis
REDIS_URL=redis://localhost:6379/0
REDIS_MAX_CONNECTIONS=20
REDIS_SOCKET_TIMEOUT=30

# Voice Processing
WHISPER_MODEL_SIZE=small
MAX_AUDIO_DURATION=1200
MAX_AUDIO_FILE_SIZE=52428800
SUPPORTED_AUDIO_FORMATS=wav,mp3,m4a,ogg,flac

# Webhooks
WEBHOOK_BASE_URL=https://your-ngrok-url.ngrok.io

# CORS
CORS_ORIGINS=http://localhost:3000,http://127.0.0.1:3000
CORS_CREDENTIALS=true
CORS_METHODS=GET,POST,PUT,DELETE,OPTIONS
CORS_HEADERS=*

# Performance
CACHE_TTL=3600
MAX_WORKERS=4
REQUEST_TIMEOUT=30
HTTP_TIMEOUT=30
HTTP_MAX_CONNECTIONS=100
HTTP_MAX_KEEPALIVE=20

# Logging
LOG_LEVEL=INFO
LOG_FORMAT=%(asctime)s - %(name)s - %(levelname)s - %(message)s

# Contract Settings
CONTRACT_HASH_ALGORITHM=blake2b
CONTRACT_SIGNATURE_ALGORITHM=ed25519
MAX_CONTRACT_DURATION=31536000
CONTRACT_CONFIRMATION_TIMEOUT=86400

# Payment Settings
ESCROW_TIMEOUT=604800
PAYMENT_RETRY_ATTEMPTS=3
PAYMENT_RETRY_DELAY=300
MIN_PAYMENT_AMOUNT=100
MAX_PAYMENT_AMOUNT=1000000

Client Environment Configuration

The Next.js client uses environment variables prefixed with NEXT_PUBLIC_ for client-side access.

Creating the Client Environment File

  1. Navigate to the client directory:
cd client
  1. Create a .env.local file:
touch .env.local
Never commit .env.local to version control. Add it to .gitignore.

Client Environment Variables

# API Endpoints (REQUIRED)
NEXT_PUBLIC_API_BASE_URL=http://localhost:8000
NEXT_PUBLIC_WEBSOCKET_BASE=ws://localhost:8000

# Feature Flags
NEXT_PUBLIC_FEATURE_LOW_DATA_MODE=true
NEXT_PUBLIC_FEATURE_ESCROW_TIMELINE=true
NEXT_PUBLIC_FEATURE_ROLE_AWARE_DASHBOARD=false
NEXT_PUBLIC_FEATURE_I18N=false

# Analytics & Monitoring (Optional)
NEXT_PUBLIC_SENTRY_DSN=
NEXT_PUBLIC_GA_MEASUREMENT_ID=
Production Client Configuration:
NEXT_PUBLIC_API_BASE_URL=https://api.voicepact.com
NEXT_PUBLIC_WEBSOCKET_BASE=wss://api.voicepact.com
NEXT_PUBLIC_FEATURE_LOW_DATA_MODE=true
NEXT_PUBLIC_FEATURE_ESCROW_TIMELINE=true
NEXT_PUBLIC_FEATURE_ROLE_AWARE_DASHBOARD=true
NEXT_PUBLIC_FEATURE_I18N=true
NEXT_PUBLIC_SENTRY_DSN=https://[email protected]/project-id

Environment-Specific Configurations

Development Environment

Backend:
  • ENVIRONMENT=development
  • DEBUG=true
  • DATABASE_ECHO=true (optional, for debugging SQL)
  • LOG_LEVEL=DEBUG
  • Use sandbox for Africa’s Talking
  • Local Redis and SQLite
Client:
  • Point to local backend (http://localhost:8000)
  • Enable all feature flags for testing
  • No analytics/monitoring needed

Testing Environment

Backend:
  • ENVIRONMENT=testing
  • DEBUG=false
  • Separate test database: DATABASE_URL=sqlite:///./voicepact_test.db
  • Mock external APIs or use sandbox

Production Environment

Production environments require additional security measures. Review the Production Deployment guide.
Backend:
  • ENVIRONMENT=production
  • DEBUG=false
  • PostgreSQL database
  • Redis with authentication
  • Strong, unique security keys
  • Production Africa’s Talking credentials
  • HTTPS webhook URLs
  • Restricted CORS origins
  • LOG_LEVEL=WARNING or INFO
  • File-based logging
Client:
  • HTTPS API endpoints (wss:// for WebSocket)
  • Production feature flags
  • Sentry for error tracking
  • Analytics enabled

Validation

Backend Configuration Validation

The backend automatically validates configuration on startup using Pydantic:
cd server
source venv/bin/activate
python -c "from app.core.config import get_settings; settings = get_settings(); print('Configuration valid!')"
Common validation errors:
  • Missing required fields (e.g., AT_API_KEY)
  • Invalid environment value (must be: development, testing, or production)
  • Invalid Whisper model size
  • Invalid log level
  • Payment amount constraints violation

Client Configuration Check

Verify client configuration:
cd client
npm run build
Check for warnings about missing NEXT_PUBLIC_* variables.

Troubleshooting

Backend Won’t Start

  1. Missing required variables:
    # Check which variables are loaded
    python -c "from app.core.config import get_settings; s = get_settings(); print(s.model_dump())"
    
  2. Database connection fails:
    • Verify SQLite file permissions
    • Check PostgreSQL connection string format
    • Ensure database server is running
  3. Redis connection fails:
    • Verify Redis is running: redis-cli ping
    • Check REDIS_URL format
    • Verify network connectivity

Client Issues

  1. API calls fail:
    • Verify NEXT_PUBLIC_API_BASE_URL is correct
    • Check CORS configuration in backend
    • Ensure backend is running
  2. WebSocket connection fails:
    • Use ws:// for HTTP and wss:// for HTTPS
    • Check firewall rules
    • Verify WebSocket route is available

Using ngrok for Local Development

To test webhooks locally:
# Start ngrok
ngrok http 8000

# Copy the HTTPS URL (e.g., https://abc123.ngrok.io)
# Update backend .env:
WEBHOOK_BASE_URL=https://abc123.ngrok.io

# Restart backend server

Security Best Practices

Follow these security practices to protect your VoicePact installation.
  1. Never commit .env or .env.local files
    • Add to .gitignore
    • Use environment-specific naming (.env.production, .env.development)
  2. Rotate secrets regularly
    • Change SECRET_KEY and other secrets periodically
    • Use a password manager or secrets management service
  3. Use strong, unique keys
    • Minimum 32 characters for secrets
    • Use secrets.token_urlsafe() for generation
  4. Restrict access in production
    • Limit CORS origins to your domains only
    • Use HTTPS/WSS exclusively
    • Enable webhook signature verification
  5. Environment isolation
    • Use different credentials for dev/staging/production
    • Separate databases and Redis instances
    • Different Africa’s Talking accounts (sandbox vs production)

Next Steps

Build docs developers (and LLMs) love