Skip to content

Commit e559e0b

Browse files
andrewm4894claude
andcommitted
Fix PostHog environment variable timing issue
- Add lazy loading function for PostHog script generation - Retry PostHog script loading with delay if env var not available at import time - This fixes the issue where POSTHOG_FRONTEND_API_KEY wasn't available during uvicorn startup on Fly 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
1 parent 6bd5eb9 commit e559e0b

File tree

1 file changed

+18
-6
lines changed

1 file changed

+18
-6
lines changed

dashboard/app.py

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -45,12 +45,24 @@ def load_env_with_custom_path():
4545

4646
log = logging.getLogger("anomstack_dashboard")
4747

48-
# Get PostHog frontend API key for analytics tracking (separate from POSTHOG_API_KEY used for metrics ingestion)
49-
posthog_api_key = os.getenv("POSTHOG_FRONTEND_API_KEY")
50-
posthog_script = None
51-
if posthog_api_key:
52-
from dashboard.constants import POSTHOG_SCRIPT
53-
posthog_script = POSTHOG_SCRIPT.replace("window.POSTHOG_API_KEY || ''", f"'{posthog_api_key}'")
48+
# PostHog script generation function (lazy loading to ensure env vars are available)
49+
def get_posthog_script():
50+
"""Generate PostHog script with API key if available."""
51+
posthog_api_key = os.getenv("POSTHOG_FRONTEND_API_KEY")
52+
if posthog_api_key:
53+
from dashboard.constants import POSTHOG_SCRIPT
54+
return POSTHOG_SCRIPT.replace("window.POSTHOG_API_KEY || ''", f"'{posthog_api_key}'")
55+
return None
56+
57+
# Get PostHog script at import time (will be None if env var not available yet)
58+
posthog_script = get_posthog_script()
59+
60+
# If PostHog script is not available at import time, try again after a short delay
61+
# This handles cases where environment variables aren't fully loaded during module import
62+
if not posthog_script:
63+
import time
64+
time.sleep(0.1) # Brief delay to allow env vars to load
65+
posthog_script = get_posthog_script()
5466

5567
# Define the app
5668
app, rt = fast_app(

0 commit comments

Comments
 (0)