Environment Configuration Changes

Overview

The system has been refactored to support per-request environment configuration instead of a global IS_SANDBOX flag. This allows the API to handle both production and sandbox environments simultaneously.

Changes Made

1. Removed Global Configuration

  • Removed IS_SANDBOX from /backend/plans/config.ts
  • Environment is now determined per-request

2. Environment Parameter Support

Clients can specify the environment using:

  • Header: X-Environment: SANDBOX or X-Environment: PRODUCTION
  • Query Parameter: ?environment=sandbox or ?environment=production
  • Default: PRODUCTION (when not specified)

3. Updated Functions

All database query functions now accept an optional environment parameter:

  • getPlanDetails(customerId, environment)
  • getLatestSubscriptionPrice(customerId, environment)
  • getSubscriptionHistory(customerId, environment)
  • getNonExpiringBalance(customerId, environment)
  • listGrants(customerId, environment)
  • ensureFreeGrant(customerId, amount, environment)
  • getUserUsageStats(customerId, environment)

4. API Endpoints

All endpoints now respect the environment parameter:

  • /api/usage
  • /api/credits/balance
  • /admin/credits/:customerId
  • All endpoints using the authenticateUser middleware

5. Webhook Behavior (Unchanged)

The webhook continues to:

  • Process ALL incoming events (both sandbox and production)
  • Store events with their actual environment from RevenueCat
  • No filtering at webhook level

Benefits

  1. No Breaking Changes: Production clients work by default without any code changes
  2. Flexible Testing: Test devices can opt into sandbox mode without code deployment
  3. Environment Isolation: Sandbox and production data remain completely separate
  4. Per-Request Control: Different clients can use different environments simultaneously

Usage Examples

Default (Production)

curl https://api.example.com/api/credits/balance \ -H "Authorization: Bearer CUSTOMER_ID"

Sandbox via Header

curl https://api.example.com/api/credits/balance \ -H "Authorization: Bearer CUSTOMER_ID" \ -H "X-Environment: SANDBOX"

Sandbox via Query Parameter

curl https://api.example.com/api/credits/balance?environment=sandbox \ -H "Authorization: Bearer CUSTOMER_ID"

Testing

Run the test script to verify the changes:

chmod +x test-environment-config.sh ./test-environment-config.sh

Important Notes

  1. Production by Default: All requests default to PRODUCTION unless explicitly set to SANDBOX
  2. Case Insensitive: Environment values are case-insensitive (sandbox, SANDBOX, Sandbox all work)
  3. Data Isolation: Sandbox and production data (subscriptions, credits, grants) are completely isolated
  4. Webhook Processing: The webhook stores events with their actual environment, regardless of any configuration