How to use server-side flag evaluation on PostHog
Server-side flag evaluation in PostHog allows you to evaluate feature flags on your server without making API calls for each request. This involves installing a PostHog SDK, initializing it with your project API key, and using the evaluate flag methods to check feature flag states programmatically.
Prerequisites
- PostHog account with project access
- Server-side SDK installed (Python, Node.js, PHP, etc.)
- Basic understanding of feature flags
- API access token or personal API key
Step-by-Step Instructions
Install PostHog Server-Side SDK
pip install posthog, for Node.js: npm install posthog-node, for PHP: composer require posthog/posthog-php. Choose the SDK that matches your backend technology stack.Initialize PostHog Client
import posthog
posthog.api_key = 'your-project-api-key'
posthog.host = 'https://app.posthog.com' For Node.js: const PostHog = require('posthog-node')
const client = new PostHog('your-project-api-key')Enable Local Evaluation
personal_api_key parameter. This allows the SDK to fetch flag definitions and evaluate them locally: posthog.personal_api_key = 'your-personal-api-key'
posthog.poll_interval = 30 # secondsCreate Feature Flag in PostHog Dashboard
Evaluate Feature Flag in Code
is_feature_enabled method to check if a feature flag is enabled for a specific user. Example: is_enabled = posthog.is_feature_enabled(
'new-checkout-flow',
'user-123',
person_properties={'email': 'user@example.com'}
)Handle Flag Variants
get_feature_flag to retrieve the specific variant value: variant = posthog.get_feature_flag(
'checkout-button-color',
'user-123',
person_properties={'plan': 'premium'}
)
if variant == 'red':
# Show red buttonImplement Error Handling
try:
is_enabled = posthog.is_feature_enabled('feature-key', user_id)
except Exception as e:
# Log error and use default behavior
is_enabled = FalseMonitor Flag Performance
Common Issues & Troubleshooting
Feature flag always returns false or None
Verify your personal API key is correct and has proper permissions. Check that the flag is Active in the PostHog dashboard and that your user meets the targeting conditions.
SDK throws authentication errors
Ensure both api_key (project key) and personal_api_key are set correctly. Verify the keys haven't expired and have appropriate permissions in Project Settings → API Keys.
Flag evaluation is slow or timing out
Reduce the poll_interval setting and check your network connectivity to PostHog servers. Consider implementing caching mechanisms and ensure you're not making excessive API calls.
Flag changes not reflecting immediately
Local evaluation caches flag definitions based on your poll_interval setting. Wait for the next poll cycle or restart your application. For immediate updates, consider using posthog.reload_feature_flags() method.