Authentication overview
PostHog's authentication system is designed to secure access to your analytics instance and protect the integrity of your product data. It distinguishes between two primary types of API keys: Project API Keys and Personal API Keys. Project API Keys are used for client-side and server-side event ingestion, ensuring data streams are directed to the correct project. Personal API Keys, conversely, grant access to the PostHog API for programmatic administration, such as managing feature flags, retrieving analytics data, or automating tasks. Understanding the distinct roles of these keys is fundamental for secure and effective integration with PostHog's platform, whether you are using its cloud service or a self-hosted instance.
The system prioritizes ease of use for developers while maintaining robust security controls. For instance, Project API Keys are often exposed in client-side code for tracking purposes, but they are designed with limited permissions to prevent unauthorized access to sensitive data or administrative functions. Personal API Keys, on the other hand, carry broader permissions and require more stringent security practices, such as being stored in secure environments and rotated regularly. This layered approach helps protect against various attack vectors, from compromised client-side code to unauthorized backend API calls, aligning with general API security principles outlined by organizations like the IETF's OAuth security topics.
Supported authentication methods
PostHog primarily supports authentication through API keys, tailored for different use cases and security profiles. These keys serve as bearer tokens for authorizing requests to the PostHog API and for identifying incoming events to a specific project.
Project API Key
- Purpose: Used for sending events to a specific PostHog project. This is the key you typically include in your SDK initializations on both frontend and backend applications.
- Permissions: Limited to event ingestion. It cannot be used to read sensitive project data or perform administrative actions via the API.
- Security Considerations: While often exposed in client-side code (e.g., JavaScript SDKs), its limited permissions mitigate the risk of compromise. However, it should still be treated as a sensitive credential.
- Example Use Case: Initializing the PostHog JavaScript SDK on your website or mobile app to capture user events and session replays.
Personal API Key
- Purpose: Provides access to the PostHog API for administrative and programmatic tasks. This key is used for tasks like retrieving analytical data, managing feature flags, or integrating with other backend systems.
- Permissions: Grants broader access, corresponding to the permissions of the user who generated the key.
- Security Considerations: This is a highly sensitive credential. It should never be exposed in client-side code and must be stored securely, ideally in environment variables or a secret management service. Regular rotation is recommended.
- Example Use Case: Running a Python script to export historical event data or automate the creation of new feature flags.
The following table summarizes PostHog's primary authentication methods:
| Method | When to Use | Security Level |
|---|---|---|
| Project API Key | Sending events from client-side (web, mobile) and server-side applications | Moderate (limited permissions, often client-side) |
| Personal API Key | Accessing the PostHog API for administrative tasks, data retrieval, and backend integrations | High (broad permissions, never client-side) |
Getting your credentials
Accessing your PostHog API credentials involves a straightforward process through the PostHog user interface. Both Project API Keys and Personal API Keys are generated and managed within your project settings.
Project API Key retrieval
- Navigate to Project Settings: Log into your PostHog instance (cloud or self-hosted) and select the project you wish to configure.
- Locate Project API Key: Go to the "Project Settings" section. Your Project API Key will typically be prominently displayed under an "API Keys" or "General Settings" tab. It's often labeled as 'Project API Key' or similar.
- Copy the Key: Copy the displayed key. This is the credential you will use to initialize PostHog SDKs in your applications. For detailed instructions, refer to the PostHog getting started installation guide.
Personal API Key generation
- Access Personal Settings: From your PostHog dashboard, click on your profile icon (usually in the top right corner) and select "Account Settings" or "Personal API Keys".
- Generate New Key: Within the Personal API Keys section, you will find an option to "Generate new personal API key". Click this button.
- Name and Permissions: You may be prompted to give the key a descriptive name (e.g., "Data Export Script") and, depending on your PostHog version or role, potentially assign specific permissions. Always grant the minimum necessary permissions.
- Copy and Store: Once generated, the Personal API Key will be displayed. Copy it immediately as it will only be shown once. Store this key securely, as it grants significant access to your PostHog data and configuration.
- Revocation: If a Personal API Key is compromised or no longer needed, you can revoke it from this same section in your Account Settings to invalidate it immediately. More details on key management are available in the PostHog personal API key documentation.
Authenticated request example
Authenticated requests to PostHog typically involve including the API key in the request header or as part of the payload, depending on the endpoint. For event ingestion, SDKs handle this automatically. For direct API interaction using a Personal API Key, you generally use an HTTP Authorization header.
Example: Sending an event with Project API Key (JavaScript SDK)
When using the PostHog JavaScript SDK, your Project API Key is initialized during setup, and subsequent event calls automatically include it:
import posthog from 'posthog-js'
posthog.init('YOUR_PROJECT_API_KEY', { api_host: 'https://app.posthog.com' })
// Send an event
posthog.capture('user_signed_up', { plan: 'premium' })
In this example, YOUR_PROJECT_API_KEY refers to the key obtained from your PostHog project settings. The SDK manages sending this key with each captured event.
Example: Making an authenticated API call with Personal API Key (Python)
For administrative tasks or data retrieval, you typically use a Personal API Key with an Authorization header.
import requests
import os
POSTHOG_API_KEY = os.environ.get("POSTHOG_PERSONAL_API_KEY") # Stored securely as an environment variable
POSTHOG_API_HOST = "https://app.posthog.com"
headers = {
"Authorization": f"Bearer {POSTHOG_API_KEY}",
"Content-Type": "application/json"
}
# Example: Fetching feature flags for a project (replace with your project ID)
project_id = 12345
response = requests.get(f"{POSTHOG_API_HOST}/api/projects/{project_id}/feature_flags/", headers=headers)
if response.status_code == 200:
feature_flags = response.json()
print("Feature Flags:", feature_flags)
else:
print(f"Error fetching feature flags: {response.status_code} - {response.text}")
This Python example demonstrates fetching feature flags using a Personal API Key. The key is retrieved from an environment variable for security, then included in the Authorization: Bearer header. Always ensure your Personal API Keys are handled on the server-side and never exposed in client-facing code.
Security best practices
Securing your PostHog credentials and API interactions is critical for protecting your data and maintaining the integrity of your analytics. Adhering to these best practices will help mitigate common security risks.
1. Secure storage of Personal API Keys
- Environment Variables: Store Personal API Keys as environment variables in your server-side applications. This prevents them from being hardcoded in your source files, which could lead to accidental exposure in version control systems.
- Secret Management Services: For more complex deployments, utilize dedicated secret management services like AWS Secrets Manager, Google Secret Manager, or HashiCorp Vault. These services provide centralized, secure storage and controlled access to sensitive credentials.
- Avoid Hardcoding: Never hardcode Personal API Keys directly into your application code, especially in frontend applications.
2. Principle of Least Privilege
- Minimal Permissions: When generating Personal API Keys, grant only the necessary permissions required for the task. If a key only needs to read data, do not give it write or administrative access. PostHog allows for granular control over user roles and permissions, which translates to the scope of Personal API Keys.
- Dedicated Keys: Create distinct Personal API Keys for different applications or services. This allows for easier revocation if a specific key is compromised without impacting other integrations.
3. Regular Key Rotation
- Periodic Rotation: Implement a policy to regularly rotate your Personal API Keys. The frequency depends on your organization's security posture and compliance requirements, but quarterly or semi-annual rotation is a common practice.
- Immediate Rotation on Compromise: If you suspect a Personal API Key has been compromised, revoke it immediately through your PostHog account settings and generate a new one. Update all applications using that key accordingly.
4. Secure Transmission
- HTTPS/TLS: PostHog's API endpoints require HTTPS for all communication, ensuring that your API keys and data are encrypted in transit. Always verify that your applications are communicating with PostHog over a secure TLS connection. This is a fundamental principle of API security best practices.
- Network Controls: If self-hosting PostHog, consider network access controls such as firewalls and VPNs to restrict access to your PostHog instance and API endpoints to authorized networks only.
5. Monitoring and Auditing
- Access Logs: Regularly review access logs for your PostHog instance (if self-hosted) or audit logs within the PostHog platform to detect any suspicious or unauthorized API access attempts.
- Alerting: Set up alerts for unusual activity patterns or repeated authentication failures, which could indicate a brute-force attack or attempted unauthorized access.
6. Client-Side Considerations for Project API Keys
- Domain Whitelisting: If supported by your PostHog instance configuration, restrict the domains from which events can be sent using your Project API Key. This can prevent unauthorized parties from sending bogus data to your project.
- Content Security Policy (CSP): Implement a strong Content Security Policy on your web applications to mitigate cross-site scripting (XSS) attacks, which could potentially expose client-side API keys, even with their limited permissions.