SDKs overview
PostHog provides a range of Software Development Kits (SDKs) designed to facilitate the integration of its product analytics, feature flagging, and experimentation features into various applications and platforms. These SDKs handle the complexities of data collection, including event tracking, user identification, and property management, allowing developers to focus on application logic. The primary function of a PostHog SDK is to send data from an application to a PostHog instance, whether it's a cloud-hosted service or a self-hosted deployment. The data typically includes user actions (events), user properties, and session information.
Each SDK is tailored to the conventions and best practices of its respective programming language or framework. This includes handling tasks such as network requests, data serialization, and sometimes offline caching or batching of events to optimize performance and resource usage. Developers can utilize these tools to instrument their applications for detailed product usage analysis, implement dynamic feature rollouts, and conduct controlled A/B tests to inform product decisions. The availability of SDKs for both front-end and back-end environments ensures comprehensive data coverage across the entire user journey.
Official SDKs by language
PostHog maintains official SDKs for a variety of popular programming languages and platforms. These SDKs are actively developed and supported by the PostHog team, ensuring compatibility with the latest platform features and adherence to best practices for data collection and security. The official SDKs are the recommended method for integrating PostHog into an application due to their robust feature sets, comprehensive documentation, and ongoing maintenance.
| Language/Platform | Package/Module Name | Installation Command (Example) | Maturity |
|---|---|---|---|
| JavaScript (Web) | posthog-js |
npm install posthog-js or yarn add posthog-js |
Stable |
| Python | posthog |
pip install posthog |
Stable |
| Node.js | posthog-node |
npm install posthog-node or yarn add posthog-node |
Stable |
| Ruby | posthog-ruby |
gem install posthog-ruby |
Stable |
| Go | posthog/posthog-go |
go get github.com/posthog/posthog-go |
Stable |
| PHP | posthog/posthog-php |
composer require posthog/posthog-php |
Stable |
| iOS (Swift/Objective-C) | PostHog (CocoaPods/Swift Package Manager) |
Podfile: pod 'PostHog' |
Stable |
| Android (Kotlin/Java) | com.posthog.android:posthog (Gradle) |
build.gradle: implementation 'com.posthog.android:posthog:+' |
Stable |
| React Native | posthog-react-native |
npm install posthog-react-native |
Stable |
| Flutter | posthog_flutter |
pubspec.yaml: posthog_flutter: ^latest_version |
Stable |
| Elixir | posthog_ex |
mix.exs: {:posthog_ex, "~> x.x"} |
Stable |
| Rust | posthog-rs |
Cargo.toml: posthog = "x.x" |
Stable |
| Haskell | posthog-haskell |
cabal file: build-depends: posthog-haskell |
Stable |
| Java | com.posthog.java:posthog (Maven/Gradle) |
Maven: <dependency> <groupId>com.posthog.java</groupId> <artifactId>posthog</artifactId> <version>x.x.x</version> </dependency> |
Stable |
Installation
The installation process for PostHog SDKs typically involves adding the relevant package or dependency to your project's configuration file and then initializing the SDK with your project API key and instance host. Specific steps vary by language and platform, but the general pattern remains consistent.
JavaScript (Web)
For web projects, the posthog-js library can be installed via npm or yarn, or included directly via a CDN. After installation, it needs to be initialized with your PostHog project API key and the URL of your PostHog instance (either cloud or self-hosted).
// Via npm/yarn
// npm install posthog-js
// import posthog from 'posthog-js'
// Or via CDN in HTML <head>
// <script>
// !function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");o.length=t;return function(e){if(typeof e!=="object")return;if(Array.isArray(e))return;for(var i=0;i<o.length;++i)if(null==e)return;e=e[o[i]]} }(o=e._i).length,n=t.createElement("script"),p=t.body,n.type="text/javascript",n.async=!0,n.src=s.api_host+"/static/array.js",p.appendChild(n),e.set_config=function(t){},e.capture=function(t,e,i){e=e||{};e.$event_type=t,e.$timestamp=new Date().toISOString(),o.push(["capture",e,i])},e.identify=function(t,e,i){e=e||{};e.$distinct_id=t,o.push(["identify",e,i])},e.reload_config=function(){o.push(["reload_config"])},e.posthog_js_version="1.134.0",r="ph_request",e.create_only=function(t,i,s){return e},e.init(i,s,a))}(document,window.posthog||[]);
// posthog.init('YOUR_API_KEY', { api_host: 'https://app.posthog.com' })
// </script>
posthog.init('YOUR_API_KEY', { api_host: 'https://app.posthog.com' });
Python
For Python applications, the posthog library is installed using pip. After installation, you instantiate a client with your API key and host. This client object is then used to send events.
# pip install posthog
from posthog import Posthog
posthog = Posthog(
'YOUR_API_KEY',
host='https://app.posthog.com'
)
iOS (Swift)
For iOS applications, the SDK is typically integrated via CocoaPods or Swift Package Manager. Once added to the project, it's initialized in the AppDelegate or an equivalent application lifecycle entry point.
// Podfile example:
// pod 'PostHog'
// Then run 'pod install'
import PostHog
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
PostHogSDK.shared.setup(apiKey: "YOUR_API_KEY", posthogHost: "https://app.posthog.com") {
// Configuration block (optional)
}
return true
}
Quickstart example
This quickstart demonstrates common PostHog SDK usage patterns for capturing events and identifying users. The example uses the JavaScript SDK, but the concepts apply across all official SDKs with minor syntax adjustments.
Capturing an event
Events represent actions users take within your application. They are the fundamental building blocks of product analytics. When a user clicks a button, views a page, or completes a form, an event can be captured.
// Capture a simple event
posthog.capture('signup_button_clicked');
// Capture an event with properties
posthog.capture('item_added_to_cart', {
item_id: 'SKU001',
item_name: 'Fancy Gadget',
price: 99.99,
category: 'Electronics'
});
Identifying a user
Identifying a user links anonymous activity to a known user ID and allows you to associate properties with that user. This is crucial for understanding individual user journeys and segmenting your user base.
// Identify a user with a unique ID
posthog.identify('unique_user_id_123');
// Identify a user with ID and properties
posthog.identify('unique_user_id_123', {
email: '[email protected]',
name: 'John Doe',
plan: 'Premium',
signup_date: '2023-01-15'
});
Feature flags and A/B testing
PostHog SDKs also enable client-side evaluation of feature flags and A/B tests. This allows you to control feature rollouts and experiment with different user experiences dynamically.
// Check if a feature flag is enabled for the current user
if (posthog.isFeatureEnabled('new-dashboard-ui')) {
// Render new UI
console.log('New dashboard UI is enabled');
} else {
// Render old UI
console.log('Old dashboard UI is enabled');
}
// Get a feature flag variant for A/B testing
const variant = posthog.getFeatureFlag('homepage-variant');
if (variant === 'control') {
console.log('Showing control homepage');
} else if (variant === 'experiment') {
console.log('Showing experiment homepage');
}
Community libraries
Beyond the official SDKs, the PostHog open-source community has developed and maintains a range of libraries and integrations for additional platforms and use cases. While these libraries may not receive the same level of direct support as official SDKs, they often fill gaps for niche technologies or provide specialized functionalities. Developers considering community libraries should review their documentation and maintenance status to ensure they meet project requirements.
Examples of community contributions include integrations for specific web frameworks, data ingestion from other services, or custom data processing pipelines. These contributions are typically found on platforms like GitHub and are often shared within the PostHog community forums or Discord channels. For instance, developers might find libraries for connecting PostHog with serverless functions from providers like AWS Lambda or Google Cloud Functions, or specialized connectors for content management systems. The open-source nature of PostHog encourages such extensions, expanding its ecosystem beyond the core offerings. Developers seeking to contribute or find these libraries can often start by exploring the PostHog API documentation and community repositories, or by searching on platforms like GitHub for projects tagged with "posthog" and the relevant language or framework. The extensibility of PostHog's API is a foundational element that enables these community-driven integrations, allowing external systems to interact with PostHog's data capture and analysis capabilities, similar to how other well-documented APIs foster community development. This allows for a broader range of integrations than might be offered by a vendor's first-party SDKs alone, supporting diverse development environments and use cases.