Documentation

ENV_GUIDE

docs/env/ENV_GUIDE.md

Environment Variables Guide

This document describes all environment variables used in Petunia, including where to obtain them, who owns them, and how to rotate them.

Quick Start

  1. Copy .env.example to .env.local
  2. Fill in the required variables (marked [REQUIRED])
  3. Run npm run prestart to validate
  4. Start the application with npm run dev
  5. See docs/env/VALIDATION_DECISIONS.md for current validation strategy (Zod deferred).

Required Variables

These variables must be set for the application to function.

VariableOwnerWhere to GetRotation PeriodSecurity Level
NEXT_PUBLIC_SUPABASE_URLPlatform TeamSupabase Dashboard → Settings → APINever (project-specific)Public
NEXT_PUBLIC_SUPABASE_ANON_KEYPlatform TeamSupabase Dashboard → Settings → APIRotate if exposedPublic
SUPABASE_SERVICE_ROLE_KEYPlatform TeamSupabase Dashboard → Settings → APIEvery 90 daysSecret
NEXT_PUBLIC_SITE_URLPlatform TeamYour deployment URLNeverPublic
DATABASE_URLPlatform TeamSupabase Dashboard → Settings → DatabaseNever (use connection pooling URL)Secret
SESSION_SECRETPlatform TeamGenerate with openssl rand -base64 32Every 90 daysSecret
CSRF_SECRETPlatform TeamGenerate with openssl rand -base64 32Every 90 daysSecret
CREDENTIALS_ENCRYPTION_KEYPlatform TeamGenerate with openssl rand -base64 32Every 90 daysSecret
ADMIN_API_KEYPlatform TeamGenerate with openssl rand -base64 32Every 90 daysSecret
INTERNAL_API_KEYPlatform TeamGenerate with openssl rand -base64 32Every 90 daysSecret
CRON_SECRETPlatform TeamGenerate with openssl rand -base64 32Every 90 daysSecret

Optional Variables

These variables enable additional features but are not required for core functionality.

Core Application

VariableOwnerWhere to GetRotation PeriodSecurity Level
NODE_ENVPlatform TeamSet to development, production, or testNeverPublic
NEXT_PUBLIC_API_URLPlatform TeamUsually ${NEXT_PUBLIC_SITE_URL}/apiNeverPublic
NEXT_PUBLIC_WEBSOCKET_URLPlatform TeamWebSocket endpoint URLNeverPublic
NEXT_PUBLIC_WEBSOCKET_PATHPlatform TeamWebSocket path (default: /api/socketio)NeverPublic
DIRECT_DATABASE_URLPlatform TeamDirect Postgres connection (if different from DATABASE_URL)NeverSecret

Authentication

VariableOwnerWhere to GetRotation PeriodSecurity Level
GOOGLE_CLIENT_IDIntegrations TeamGoogle Cloud Console → APIs & Services → CredentialsNeverPublic
GOOGLE_CLIENT_SECRETIntegrations TeamGoogle Cloud Console → APIs & Services → CredentialsEvery 180 daysSecret
AUTH_OTP_EXPIRYPlatform TeamOTP expiry in seconds (default: 300)NeverPublic
EMAIL_VERIFICATION_EXPIRY_HOURSPlatform TeamEmail verification link expiry (default: 24)NeverPublic
PASSWORD_RESET_EXPIRY_MINUTESPlatform TeamPassword reset link expiry (default: 30)NeverPublic
TOTP_WINDOWPlatform TeamTOTP time window for 2FA (default: 1)NeverPublic

Caching & Knowledge Base

VariableOwnerWhere to GetRotation PeriodSecurity Level
UPSTASH_REDIS_REST_URLPlatform TeamUpstash Dashboard → Redis → REST APINeverPublic
UPSTASH_REDIS_REST_TOKENPlatform TeamUpstash Dashboard → Redis → REST APIEvery 90 daysSecret
UPSTASH_VECTOR_REST_URLAI TeamUpstash Dashboard → Vector → REST APINeverPublic
UPSTASH_VECTOR_REST_TOKENAI TeamUpstash Dashboard → Vector → REST APIEvery 90 daysSecret
REDIS_URLPlatform TeamSelf-hosted Redis connection stringNeverSecret

Email Configuration

VariableOwnerWhere to GetRotation PeriodSecurity Level
GMAIL_USERPlatform TeamGmail account emailNeverPublic
GMAIL_APP_PASSWORDPlatform TeamGoogle Account → Security → App PasswordsEvery 180 daysSecret
EMAIL_FROMPlatform TeamSender email addressNeverPublic

Voice Services

VariableOwnerWhere to GetRotation PeriodSecurity Level
CARTESIA_API_KEYVoice TeamCartesia Dashboard → API KeysEvery 90 daysSecret
CARTESIA_VOICE_IDVoice TeamCartesia Dashboard → VoicesNeverSecret
ELEVENLABS_API_KEYVoice TeamElevenLabs Dashboard → Profile → API KeyEvery 90 daysSecret
NEXT_PUBLIC_ELEVENLABS_VOICE_IDVoice TeamElevenLabs Dashboard → VoicesNeverPublic
RETELL_API_KEYVoice TeamRetell Dashboard → API KeysEvery 90 daysSecret
NEXT_PUBLIC_RETELL_AGENT_IDVoice TeamRetell Dashboard → AgentsNeverPublic
NEXT_PUBLIC_RETELL_VOICE_IDVoice TeamRetell Dashboard → VoicesNeverPublic
TWILIO_ACCOUNT_SIDVoice TeamTwilio Console → Account InfoNeverPublic
TWILIO_AUTH_TOKENVoice TeamTwilio Console → Account InfoEvery 180 daysSecret
TWILIO_PHONE_NUMBERVoice TeamTwilio Console → Phone NumbersNeverPublic
RINGCENTRAL_JWT_TOKENVoice TeamRingCentral Developer Portal → JWTEvery 90 daysSecret

Third-Party Integrations

VariableOwnerWhere to GetRotation PeriodSecurity Level
YELP_CLIENT_IDIntegrations TeamYelp Developer Portal → OAuth App SettingsNeverPublic
YELP_CLIENT_SECRETIntegrations TeamYelp Developer Portal → OAuth App SettingsEvery 180 daysSecret
YELP_WEBHOOK_SECRETIntegrations TeamYelp Developer Portal → Webhook SettingsWhen endpoint changesSecret
NEXT_PUBLIC_USE_REAL_YELP_APIIntegrations TeamSet to true for productionNeverPublic
YELP_USE_WEBHOOKSIntegrations TeamEnable webhook-based syncNeverPublic
YELP_USE_PERIODIC_SYNCIntegrations TeamEnable periodic syncNeverPublic
YELP_SYNC_INTERVAL_MINUTESIntegrations TeamSync interval (default: 15)NeverPublic

Multi-Channel Communications

Twilio (SMS)

VariableOwnerWhere to GetRotation PeriodSecurity Level
TWILIO_ACCOUNT_SIDIntegrations TeamTwilio Console → Account InfoNeverPublic
TWILIO_AUTH_TOKENIntegrations TeamTwilio Console → Account InfoEvery 180 daysSecret
TWILIO_PHONE_NUMBERIntegrations TeamTwilio Console → Phone NumbersNeverPublic
TWILIO_VERIFY_SERVICE_SIDIntegrations TeamTwilio Console → Verify → ServicesNeverPublic
TWILIO_WEBHOOK_URLIntegrations TeamDefaults to ${NEXT_PUBLIC_SITE_URL}/api/webhooks/twilioNeverPublic

Facebook Integration

VariableOwnerWhere to GetRotation PeriodSecurity Level
NEXT_PUBLIC_FACEBOOK_APP_IDIntegrations TeamFacebook Developer Console → App SettingsNeverPublic
FACEBOOK_CLIENT_SECRETIntegrations TeamFacebook Developer Console → App Settings → App SecretEvery 180 daysSecret
FACEBOOK_WEBHOOK_VERIFY_TOKENIntegrations TeamCustom token you create for webhook verificationWhen endpoint changesSecret

Google Business Profile

VariableOwnerWhere to GetRotation PeriodSecurity Level
NEXT_PUBLIC_GOOGLE_CLIENT_IDIntegrations TeamGoogle Cloud Console → APIs & CredentialsNeverPublic
GOOGLE_CLIENT_SECRETIntegrations TeamGoogle Cloud Console → APIs & CredentialsEvery 180 daysSecret
GOOGLE_MAPS_API_KEYIntegrations TeamGoogle Cloud Console → APIs & Credentials → Maps API KeyEvery 180 daysSecret
GOOGLE_PUBSUB_PROJECT_IDIntegrations TeamGoogle Cloud Console → Project SettingsNeverPublic
GOOGLE_PUBSUB_SUBSCRIPTIONIntegrations TeamFormat: projects/{project}/subscriptions/{subscription}NeverPublic
GOOGLE_SERVICE_ACCOUNT_KEYIntegrations TeamGoogle Cloud Console → IAM → Service AccountsEvery 365 daysSecret

AI Services

VariableOwnerWhere to GetRotation PeriodSecurity Level
ANTHROPIC_API_KEYAI TeamAnthropic Console → API KeysEvery 90 daysSecret
PINECONE_API_KEYAI TeamPinecone Console → API KeysEvery 180 daysSecret
PINECONE_ENVIRONMENTAI TeamPinecone Console → EnvironmentNeverPublic
PINECONE_INDEX_NAMEAI TeamPinecone Console → IndexesNeverPublic

Forbidden in all environments: NEXT_PUBLIC_INTERNAL_API_KEY, NEXT_PUBLIC_ELEVENLABS_API_KEY (use server-only equivalents).

Security & Encryption

VariableOwnerWhere to GetRotation PeriodSecurity Level
NEXT_PUBLIC_WS_ENCRYPTIONPlatform TeamSet to true to enableNeverPublic
WS_ENCRYPTION_KEYPlatform TeamGenerate with openssl rand -hex 32Every 90 daysSecret
WS_SIGNING_KEYPlatform TeamGenerate with openssl rand -hex 32Every 90 daysSecret
NEXT_PUBLIC_WS_SIGN_MESSAGESPlatform TeamSet to true to enableNeverPublic
ADMIN_API_KEYPlatform TeamGenerate with openssl rand -base64 32Every 90 daysSecret
INTERNAL_API_KEYPlatform TeamGenerate with openssl rand -base64 32Every 90 daysSecret

Feature Flags

VariableOwnerWhere to GetRotation PeriodSecurity Level
FEATURE_FLAGS_PRESETProduct TeamSet to launch, full, or minimalNeverPublic
FEATURE_FLAGS_JSONProduct TeamJSON configuration objectNeverPublic
FEATURE_AUTH_SIGNUPProduct TeamSet to true to enableNeverPublic
FEATURE_ONBOARDINGProduct TeamSet to true to enableNeverPublic
FEATURE_OAUTHProduct TeamSet to true to enableNeverPublic
FEATURE_CANONICAL_PID_DASHBOARDProduct TeamSet to true to enable (default: true)NeverPublic
FEATURE_AI_CHATProduct TeamSet to true to enableNeverPublic
FEATURE_FILE_UPLOADSProduct TeamSet to true to enableNeverPublic
FEATURE_WEBHOOKSProduct TeamSet to true to enableNeverPublic

Development Settings

VariableOwnerWhere to GetRotation PeriodSecurity Level
USE_DEMO_SERVICESDevelopment TeamSet to true for developmentNeverPublic
BYPASS_AUTHDevelopment TeamDANGER: Only for local developmentNeverPublic
NEXT_PUBLIC_SKIP_AUTHDevelopment TeamDANGER: Only for local developmentNeverPublic
FORCE_DEMO_LOGINDevelopment TeamDANGER: Only for local developmentNeverPublic
SKIP_WEBSOCKET_AUTHDevelopment TeamDANGER: Only for local developmentNeverPublic
NEXT_PUBLIC_ENABLE_CLOUD_THEMEDevelopment TeamSet to true to enable cloud themeNeverPublic
LOG_LEVELDevelopment TeamSet to debug, info, warn, or errorNeverPublic

Legacy note: The old USE_MOCK_SERVICES flag has been removed. Set USE_DEMO_SERVICES=true anywhere you previously relied on the mock stack.

ML/AI Features

VariableOwnerWhere to GetRotation PeriodSecurity Level
ENABLE_ML_ADAPTIVE_LEARNINGAI TeamSet to true to enableNeverPublic
ENABLE_ML_BEHAVIORAL_ANALYSISAI TeamSet to true to enableNeverPublic
ENABLE_ML_TIMING_OPTIMIZATIONAI TeamSet to true to enableNeverPublic
ENABLE_ML_PYTORCH_MODELAI TeamSet to true to enableNeverPublic
ENABLE_ML_REALTIME_INTELLIGENCEAI TeamSet to true to enableNeverPublic
ENABLE_ML_CONTINUOUS_LEARNINGAI TeamSet to true to enableNeverPublic
ENABLE_ML_BATCH_TRAININGAI TeamSet to true to enableNeverPublic
ENABLE_ML_AUTO_ANALYSISAI TeamSet to true to enableNeverPublic
ML_ADAPTIVE_LEARNING_ROLLOUTAI TeamPercentage of users (0-100)NeverPublic
ML_BEHAVIORAL_ANALYSIS_ROLLOUTAI TeamPercentage of users (0-100)NeverPublic
ML_TIMING_OPTIMIZATION_ROLLOUTAI TeamPercentage of users (0-100)NeverPublic
ML_MAX_CONCURRENT_REQUESTSAI TeamMax concurrent requests (default: 10)NeverPublic
ML_REQUEST_TIMEOUT_MSAI TeamRequest timeout in milliseconds (default: 5000)NeverPublic
ML_CACHE_TTL_SECONDSAI TeamCache TTL in seconds (default: 300)NeverPublic
ML_SERVICE_URLAI TeamPython ML service URLNeverPublic
ML_SERVICE_API_KEYAI TeamML service API keyEvery 90 daysSecret

Rotation Procedures

Rotating Supabase Service Role Key

  1. Go to Supabase Dashboard → Settings → API
  2. Click "Reset service role key"
  3. Update SUPABASE_SERVICE_ROLE_KEY in Vercel
  4. Redeploy application
  5. Verify all services using service role are working

WARNING: This will temporarily break API calls until redeployed.

Rotating Session Secrets

  1. Generate new secret: openssl rand -base64 32
  2. Update SESSION_SECRET in Vercel
  3. WARNING: This will invalidate all existing sessions
  4. Redeploy application
  5. Monitor for user complaints about being logged out

Best Practice: Rotate these during low-traffic periods and communicate to users.

Rotating WebSocket Encryption Keys

  1. Generate new keys:
    openssl rand -hex 32  # For WS_ENCRYPTION_KEY
    openssl rand -hex 32  # For WS_SIGNING_KEY
    
  2. Update both keys simultaneously in Vercel
  3. Redeploy application
  4. WARNING: Active WebSocket connections will be dropped
  5. Monitor WebSocket connection health

Rotating Third-Party API Keys

  1. Generate new key in provider dashboard
  2. Test new key in staging environment
  3. Update key in Vercel production environment
  4. Monitor API usage for errors
  5. Revoke old key after 24 hours

Providers to rotate regularly:

  • Cartesia API Key (every 90 days)
  • ElevenLabs API Key (every 90 days)
  • Retell API Key (every 90 days)
  • Anthropic API Key (every 90 days)
  • Yelp Client Secret (every 180 days)
  • Google Client Secret (every 180 days)
  • Twilio Auth Token (every 180 days)

Rotating Admin API Keys

  1. Generate new keys:
    openssl rand -base64 32  # For ADMIN_API_KEY
    openssl rand -base64 32  # For INTERNAL_API_KEY
    
  2. Update keys in Vercel
  3. Update any internal services using these keys
  4. Redeploy application
  5. Verify admin endpoints still work
  6. Revoke old keys

Rotating Gmail App Password

  1. Go to Google Account → Security → App Passwords
  2. Revoke old password
  3. Generate new app password
  4. Update GMAIL_APP_PASSWORD in Vercel
  5. Test email sending functionality
  6. Verify no errors in logs

Security Best Practices

Secret Management

  1. Never commit secrets to version control
  2. Use Vercel environment variables for production
  3. Rotate secrets regularly according to schedule above
  4. Use different keys for development, staging, and production
  5. Monitor for exposed secrets using GitHub secret scanning
  6. Limit key permissions to minimum required scope

Key Generation

Always use cryptographically secure random generators:

# For NextAuth and session secrets (32+ characters)
openssl rand -base64 32

# For WebSocket encryption keys (32 bytes hex)
openssl rand -hex 32

# For admin API keys
openssl rand -base64 32

Never use:

  • Predictable strings
  • Dictionary words
  • Incrementing numbers
  • Previously leaked keys

Environment Separation

Maintain separate keys for each environment:

EnvironmentPurposeKey Rotation
DevelopmentLocal development with demo servicesAnnually
StagingPre-production testing with real APIsEvery 180 days
ProductionLive user-facing applicationEvery 90 days

Never use production keys in development or staging.

Access Control

Limit who can access secrets:

RoleAccess Level
DevelopersDevelopment keys only
DevOpsAll environments (read-only)
Platform TeamAll environments (full access)
AdminsProduction (full access)

Use Vercel Teams and RBAC to enforce access control.

Troubleshooting

"Missing required variable" error

Run npm run prestart to see which variables are missing. Copy .env.example to .env.local and fill in the values.

"Invalid URL format" error

Ensure URLs start with http:// or https://. For Supabase URL, always use https://.

"Session secret too short" error

SESSION_SECRET must be at least 32 characters. Generate a new one with openssl rand -base64 32.

"Database connection failed" error

Check DATABASE_URL format:

postgresql://user:password@host:port/database

For Supabase, use the connection pooling URL (includes port 6543).

"Supabase anon key invalid" error

Verify you copied the correct key from Supabase Dashboard → Settings → API. The anon key is the "public" key, not the service role key.

"NextAuth callback error" error

"WebSocket connection refused" error

Check:

  1. NEXT_PUBLIC_WEBSOCKET_URL is correct
  2. NEXT_PUBLIC_WEBSOCKET_PATH matches server path
  3. WebSocket server is running (port 3001 by default)

"Yelp OAuth redirect mismatch" error

Verify redirect URI in Yelp Developer Portal matches:

${NEXT_PUBLIC_SITE_URL}/api/auth/callback/yelp

"Voice service API key invalid" error

Check:

  1. Key is not expired
  2. Key has correct permissions
  3. Account has sufficient credits
  4. API endpoint URL is correct

Environment Variables Not Loading

If variables aren't loading in your application:

  1. Restart development server after changing .env.local
  2. Check file location: Must be in project root
  3. Check file name: Must be exactly .env.local (not .env.local.txt)
  4. Check syntax: No quotes needed, no spaces around =
  5. Check caching: Clear Next.js cache with rm -rf .next

Validation

Manual Validation

Run the prestart script to validate environment variables:

npm run prestart

This checks:

  • All required variables are present
  • URLs are valid format
  • Secrets meet minimum length requirements
  • Numeric values are within valid ranges

Automated Validation

The application validates environment variables at startup:

  1. Required variables check: Fails if missing
  2. Format validation: Warns if invalid format
  3. Security checks: Warns if using default/weak values
  4. Feature flag validation: Ensures valid preset or JSON

CI/CD Validation

In CI/CD pipelines, validate before deployment:

# In .github/workflows/deploy.yml
- name: Validate Environment
  run: npm run prestart
  env:
    # Pull from Vercel or GitHub Secrets
    SUPABASE_URL: ${{ secrets.SUPABASE_URL }}
    # ... other variables

Contact

For questions about environment variables, contact:

CategoryTeamContact
Platform variables (Supabase, Database, Sessions)Platform Teamsupport@gardenpatch.xyz
Integration variables (Yelp, Google, Facebook)Integrations Teamsupport@gardenpatch.xyz
AI/Voice variables (Cartesia, ElevenLabs, Retell, Anthropic)AI/Voice Teamsupport@gardenpatch.xyz
Security variables (Encryption keys, Admin keys)Security Teamsupport@gardenpatch.xyz
Development variables (Demo services, Feature flags)Development Teamsupport@gardenpatch.xyz

Multi-Channel Integration Setup

Twilio SMS Setup

  1. Create Twilio Account: Go to Twilio Console
  2. Get Account Credentials:
    • Account SID and Auth Token from Account Info
    • Purchase a phone number with SMS capability
  3. Configure Webhook:
    • Go to Phone Numbers → Manage → Active Numbers
    • Select your number
    • Under "Messaging", set webhook URL to:
      https://your-domain.com/api/webhooks/twilio
      
    • Method: HTTP POST
  4. Set Environment Variables:
    TWILIO_ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    TWILIO_AUTH_TOKEN=your_auth_token
    TWILIO_PHONE_NUMBER=+15551234567
    

Facebook Integration Setup

  1. Create Facebook App: Go to Facebook Developers
  2. Add Products:
    • Facebook Login
    • Messenger
  3. Configure OAuth:
    • Settings → Basic → Add Platform → Website
    • Valid OAuth Redirect URIs:
      https://your-domain.com/settings/connections/facebook/callback
      
  4. Configure Webhooks:
    • Messenger → Settings → Webhooks
    • Callback URL: https://your-domain.com/api/webhooks/facebook
    • Verify Token: Your custom FACEBOOK_WEBHOOK_VERIFY_TOKEN
    • Subscribe to: messages, messaging_postbacks
  5. Set Environment Variables:
    NEXT_PUBLIC_FACEBOOK_APP_ID=your_app_id
    FACEBOOK_CLIENT_SECRET=your_app_secret
    FACEBOOK_WEBHOOK_VERIFY_TOKEN=your_custom_verify_token
    

Google Business Profile Setup

  1. Create Google Cloud Project: Go to Google Cloud Console

  2. Enable APIs:

    • My Business Business Information API
    • My Business Account Management API
    • Cloud Pub/Sub API
  3. Create OAuth Credentials:

    • APIs & Services → Credentials → Create Credentials → OAuth 2.0 Client ID
    • Application type: Web application
    • Authorized redirect URIs:
      https://your-domain.com/settings/connections/google/callback
      
  4. Configure Pub/Sub (for real-time notifications):

    # Create topic
    gcloud pubsub topics create petunia-google-notifications
    
    # Create push subscription
    gcloud pubsub subscriptions create petunia-google-sub \
      --topic=petunia-google-notifications \
      --push-endpoint=https://your-domain.com/api/webhooks/google \
      --push-auth-service-account=your-sa@project.iam.gserviceaccount.com
    
  5. Set Environment Variables:

    NEXT_PUBLIC_GOOGLE_CLIENT_ID=your_client_id.apps.googleusercontent.com
    GOOGLE_CLIENT_SECRET=your_client_secret
    GOOGLE_PUBSUB_PROJECT_ID=your-gcp-project
    GOOGLE_PUBSUB_SUBSCRIPTION=projects/your-project/subscriptions/petunia-google-sub
    

Additional Resources