Kotlin Multiplatform

Contents

The PostHog Kotlin Multiplatform (KMP) SDK lets you capture analytics from shared Kotlin code that runs on Android, iOS, the web, and JVM desktop apps. It's a thin wrapper that delegates to the official PostHog SDKs on each target – Android, iOS, JavaScript, and the JVM core library on desktop – so you get native batching, queueing, and session replay behind a single common API.

Early access: This SDK is currently in a 0.x pre-release. The API may change between minor versions until it stabilizes. We'd love your feedback on GitHub.

Install with the wizard

Run this command in your project directory to add PostHog to your Kotlin Multiplatform project. The wizard detects your framework, installs the SDK, and sets up your first events.

Learn more

Or set it up manually by following the rest of this guide.

Installation

Add the dependency to your shared module's commonMain source set:

shared/build.gradle.kts
kotlin {
sourceSets {
commonMain.dependencies {
implementation("com.posthog:posthog-kmp:<version>")
}
}
}

If you use a Gradle version catalog, declare it there instead:

gradle/libs.versions.toml
[versions]
posthog-kmp = "<version>"
[libraries]
posthog-kmp = { group = "com.posthog", name = "posthog-kmp", version.ref = "posthog-kmp" }

You can find the latest version on Maven Central.

Note: This setup applies to posthog-kmp 0.5.0 and later and requires Kotlin 2.4.0 or later.

On iOS, the SDK uses Kotlin's Swift Package Manager (SwiftPM) integration to link the native posthog-ios package and copy its resources, including privacy manifests, into your app.

posthog-kmp 0.7.0 and later requires iOS 15 or later. posthog-kmp 0.11.0 and later requires Xcode 26 or later to build, and macOS 11 or later for macOS targets.

After adding the dependency, run the linkage task once from your project root:

Terminal
XCODEPROJ_PATH="$PWD/iosApp/iosApp.xcodeproj" \
./gradlew :shared:integrateLinkagePackage

Replace iosApp/iosApp.xcodeproj with the path to your Xcode project and :shared with the Gradle module that builds your iOS framework.

The task generates a KotlinMultiplatformLinkedPackage directory and adds it to the Xcode project. Commit the generated package and Xcode project changes. The package is updated automatically when SwiftPM dependencies change. If the first build after a dependency change stops with Synthetic project state updated, run the same build again. You don't need to add posthog-ios to Xcode separately.

Configure the SDK

Initialize PostHog once, early in your app's lifecycle, by calling PostHog.setup() with a PostHogConfig and a platform PostHogContext:

Kotlin
import com.posthog.kmp.PostHog
import com.posthog.kmp.PostHogConfig
import com.posthog.kmp.PostHogContext
PostHog.setup(
config = PostHogConfig(
projectToken = "<ph_project_token>",
host = "https://us.i.posthog.com",
),
context = PostHogContext(), // platform-specific, see below
)

You can find your project token and host in your project settings. For convenience, PostHogConfig.HOST_US and PostHogConfig.HOST_EU are provided as constants for the two PostHog Cloud hosts.

Use your project token (phc_...), not a personal API key. From posthog-kmp 0.11.0, the SDK stays disabled on Android, iOS, macOS and the JVM if projectToken is a personal API key (phx_...).

Note: From posthog-kmp 0.11.0, Android, iOS, macOS and the JVM send events to /i/v1/analytics/events. If host points to a reverse proxy or a self-hosted instance, make sure it forwards that path and passes the request headers and PostHog's response through unchanged. Refer to Upgrade to 0.11.0 below for the full list.

Platform-specific setup

The only platform difference is how you build PostHogContext. Everything else – event capture, feature flags, config – is shared code.

Android

Android requires the Application instance, so call setup from your Application class – not from an Activity, whose onCreate re-runs on every recreation (for example, on rotation):

Kotlin
import android.app.Application
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
PostHog.setup(
config = PostHogConfig(projectToken = "<ph_project_token>"),
context = PostHogContext(this),
)
}
}

Register the class in your AndroidManifest.xml:

XML
<application android:name=".MyApplication" ...>

iOS

On iOS, use the no-argument PostHogContext():

Kotlin
// MainViewController.kt
fun MainViewController() = ComposeUIViewController {
LaunchedEffect(Unit) {
PostHog.setup(
config = PostHogConfig(projectToken = "<ph_project_token>"),
context = PostHogContext(),
)
}
App()
}

Web

On the web, use the no-argument PostHogContext():

Kotlin
// main.kt
fun main() {
PostHog.setup(
config = PostHogConfig(projectToken = "<ph_project_token>"),
context = PostHogContext(),
)
}

JVM (desktop)

On the JVM – for example, a Compose Multiplatform desktop app – use the no-argument PostHogContext():

Kotlin
// main.kt
fun main() = application {
PostHog.setup(
config = PostHogConfig(projectToken = "<ph_project_token>"),
context = PostHogContext(),
)
Window(onCloseRequest = ::exitApplication) { App() }
}
Configure Compose Desktop release builds

If you package your app with Compose Desktop, add jdk.unsupported and a ProGuard configuration file to the compose.desktop.application block in your app module's build.gradle.kts:

composeApp/build.gradle.kts
compose.desktop {
application {
buildTypes.release.proguard {
configurationFiles.from(project.file("compose-desktop.pro"))
}
nativeDistributions {
modules("jdk.unsupported")
}
}
}

If you already configure nativeDistributions.modules, add jdk.unsupported to the existing list.

Create compose-desktop.pro next to the module's build.gradle.kts:

composeApp/compose-desktop.pro
# PostHog uses Gson reflection for its queue and API payloads.
-keepattributes Signature,*Annotation*
-keep class com.posthog.** { *; }
-keep class com.google.gson.** { *; }
# Compose Desktop's ProGuard optimizer can produce invalid Okio bridge return types.
-keep class okio.** { *; }
# OkHttp probes optional platform and TLS provider classes at runtime.
-dontwarn android.**
-dontwarn dalvik.**
-dontwarn javax.annotation.**
-dontwarn org.bouncycastle.**
-dontwarn org.conscrypt.**
-dontwarn org.openjsse.**
-dontwarn org.codehaus.mojo.animal_sniffer.**
-dontwarn com.jetbrains.SharedTextures
-adaptresourcefilenames okhttp3/internal/publicsuffix/PublicSuffixDatabase.gz

Compose Desktop creates release distributions with ProGuard and a custom Java runtime built by jlink. The custom runtime doesn't include jdk.unsupported automatically, but Gson uses APIs from this module when it deserializes PostHog's queued events and API models. The ProGuard rules preserve reflection-based PostHog and Gson models, prevent invalid Okio bytecode optimization, and retain the OkHttp resources required at runtime.

You must configure both settings in your application because Compose Desktop owns the application's ProGuard and jlink configuration. Dependencies such as the PostHog KMP SDK can't modify this release packaging configuration.

On the JVM, the SDK persists its offline event queue and identity cache to disk under ~/.posthog-kmp. If user.home isn't set (for example, in some containers), it falls back to the temp directory and logs a warning.

Capturing events

You can send custom events using capture:

Kotlin
PostHog.capture("user_signed_up")

You can add properties to any event by passing a properties map:

Kotlin
PostHog.capture(
event = "purchase_completed",
properties = mapOf(
"product_id" to "SKU123",
"price" to 29.99,
"currency" to "USD",
),
)

To attach group context or a custom timestamp to a single event, pass CaptureOptions:

Kotlin
import com.posthog.kmp.CaptureOptions
PostHog.capture(
event = "feature_used",
properties = mapOf("feature_name" to "export"),
options = CaptureOptions(groups = mapOf("company" to "acme_corp")),
)

Note: Properties with null values are dropped before the event is sent, so every platform receives the same event shape.

Event options

From posthog-kmp 0.11.0, settings that tell PostHog how to process an event are sent as event options, apart from its properties. Pass them in CaptureOptions.eventOptions, or in the eventOptions parameter of screen(), identify(), alias(), group(), setPersonProperties(), and captureException(). PostHogEventOptions has the keys:

OptionReplaces the property
PostHogEventOptions.PROCESS_PERSON_PROFILE$process_person_profile
PostHogEventOptions.COOKIELESS_MODE$cookieless_mode
PostHogEventOptions.DISABLE_SKEW_CORRECTION$ignore_sent_at
PostHogEventOptions.PRODUCT_TOUR_ID$product_tour_id

Kotlin
import com.posthog.kmp.PostHogEventOptions
PostHog.capture(
event = "checkout",
options = CaptureOptions(eventOptions = mapOf(PostHogEventOptions.COOKIELESS_MODE to true)),
)
// Send an option with every later event, until you unregister it or call reset()
PostHog.registerOptions(mapOf(PostHogEventOptions.COOKIELESS_MODE to true))
PostHog.unregisterOptions(PostHogEventOptions.COOKIELESS_MODE)

The legacy properties still work, and an option wins over its property. On Android, iOS, macOS, and the JVM, options are sent as given, so a key not in the table also works. On JavaScript and Wasm, PostHog.js has no options, so the keys in the table are sent as their properties on capture(), screen(), and captureException() events, and other keys are dropped. registerOptions() registers those keys as their properties and drops other keys. identify(), alias(), group(), and setPersonProperties() drop their options there, because PostHog.js sends those events without event properties. PROCESS_PERSON_PROFILE has no effect there, because PostHog.js sets $process_person_profile itself.

AI events

To send AI observability events you build yourself, such as $ai_generation, $ai_span, or $ai_embedding, call captureAi instead of capture. It's available from posthog-kmp 0.11.0 on Android, iOS, macOS, and the JVM. It takes the same arguments as capture and runs the same beforeSend callbacks, then sends the event to PostHog's AI endpoint, which accepts much larger events than capture.

Kotlin
val uuid = PostHog.captureAi(
event = "\$ai_generation",
properties = mapOf(
"\$ai_trace_id" to traceId,
"\$ai_model" to "gpt-5",
"\$ai_provider" to "openai",
"\$ai_input_tokens" to 120,
"\$ai_output_tokens" to 45,
),
)

captureAi returns the event's UUID once the event is queued. It returns null when the event isn't queued: the SDK isn't set up, is disabled or opted out, a beforeSend callback dropped the event, or the event is over captureAiMaxEventBytes. On JavaScript and Wasm, it sends nothing and returns null.

  • Separate queue. AI events have their own on-disk queue, so large events don't push your other events out. It keeps up to captureAiMaxQueueSize events and at most 50 MiB. Past either limit, the oldest events are dropped.
  • Size limit. The SDK drops an AI event that's over 8 MiB plus 64 KiB once serialized. Everything you pass is sent as is. The SDK doesn't truncate or redact prompts, outputs, or media.
  • capture doesn't reroute AI events. capture never sends $ai_ events to the AI endpoint, so use captureAi for them. PostHog drops an event sent with captureAi whose name doesn't start with $ai_.
  • Reverse proxies. captureAi sends to /i/v1/ai/events. If host points to a reverse proxy or a self-hosted instance, it has to serve that path too, with the same headers and responses as /i/v1/analytics/events.

These PostHogConfig settings apply only to captureAi, and are ignored on JavaScript and Wasm:

SettingDefaultDescription
captureAiCompressionPostHogCompression.GZIPHow captureAi request bodies are compressed. Other requests aren't affected.
captureAiMaxQueueSize100Maximum number of AI events kept on disk before the oldest are dropped. The 50 MiB limit applies too.
captureAiTimeout60Seconds an AI request can go without network activity before it times out.
captureAiMaxEventBytes8454144 (8 MiB + 64 KiB)Maximum size of a serialized AI event. You can only lower it: a larger value uses the default.

A value of 0 or less for a numeric setting uses its default.

Filter events before sending

beforeSend is available in PostHog KMP 0.3.0 and later on Android, iOS, JVM, Kotlin/JS, and Kotlin/Wasm, and in 0.6.0 and later on macOS. Use version 0.4.2 or later for the exception behavior described below.

Add one or more PostHogBeforeSend callbacks to PostHogConfig.beforeSend. Return a copied event to modify its name or distinct ID, or to redact properties. Return null to drop the event before the SDK queues it:

Kotlin
import com.posthog.kmp.PostHog
import com.posthog.kmp.PostHogBeforeSend
import com.posthog.kmp.PostHogConfig
import com.posthog.kmp.PostHogContext
val config = PostHogConfig(
projectToken = "<ph_project_token>",
beforeSend = listOf(
PostHogBeforeSend { event ->
event.copy(properties = event.properties - "email")
},
PostHogBeforeSend { event ->
if (event.event == "internal_debug_event") null else event
},
),
)
PostHog.setup(
config = config,
context = PostHogContext(),
)

Callbacks run synchronously in list order. Each callback receives the event returned by the previous callback. Returning null skips the remaining callbacks. If a callback throws, the SDK drops the event and skips the remaining callbacks.

From posthog-kmp 0.11.0, event.options holds the event's event options, including the ones the SDK set, such as process_person_profile set to false for an anonymous user's event. Return a copy with changed options to change them. On JavaScript and Wasm, options is always null.

Versions 0.3.0 through 0.4.1 ignore a callback exception and continue with the last valid event.

Identifying users

Identifying users is required. Call posthog.identify('your-user-id') after login to link events to a known user. This is what connects frontend event captures, session replays, LLM traces, and error tracking to the same person — and lets backend events link back too.

Use a stable ID from your auth system when possible, not an email or display name. Send those as person properties instead. If your app has no other stable key, email works as a fallback if they are unique. Never a shared literal like "anonymous" or "user", which pools many people onto one person and corrupts their data. When no ID is available at all, skip the identify and retain the anonymous distinct ID that's automatically assigned.

Call posthog.reset() on logout, so the next person to use the browser doesn't inherit the last one's identity.

See our guide on identifying users for how to set this up.

Use identify to associate events with a specific user and, optionally, set person properties:

Kotlin
PostHog.identify(
distinctId = "user_123",
userProperties = mapOf(
"email" to "user@example.com",
"plan" to "premium",
),
)

userPropertiesSetOnce works just like userProperties, except it only sets a property if the user doesn't already have it:

Kotlin
PostHog.identify(
distinctId = "user_123",
userPropertiesSetOnce = mapOf(
"first_seen" to "2025-01-01",
"signup_source" to "organic",
),
)

Anonymous and identified events

PostHog captures two types of events: anonymous and identified

Identified events enable you to attribute events to specific users, and attach person properties. They're best suited for logged-in users.

Scenarios where you want to capture identified events are:

  • Tracking logged-in users in B2B and B2C SaaS apps
  • Doing user segmented product analysis
  • Growth and marketing teams wanting to analyze the complete conversion lifecycle

Anonymous events are events without individually identifiable data. They're best suited for web analytics or apps where users aren't logged in.

Scenarios where you want to capture anonymous events are:

  • Tracking a marketing website
  • Content-focused sites
  • B2C apps where users don't sign up or log in

Under the hood, the key difference between identified and anonymous events is that for identified events we create a person profile for the user, whereas for anonymous events we do not.

Important: Due to the reduced cost of processing them, anonymous events can be up to 4x cheaper than identified ones, so we recommended you only capture identified events when needed.

Get the current user's distinct ID

You may find it helpful to get the current user's distinct ID – for example, to check whether you've already called identify for a user. Call getDistinctId(), which returns either the ID automatically generated by PostHog or the one passed to identify():

Kotlin
val distinctId = PostHog.getDistinctId()

Alias

Sometimes you want to assign multiple distinct IDs to a single user. This is helpful when your primary distinct ID is inaccessible – for example, if a distinct ID used on the frontend isn't available in your backend. Use alias to assign another distinct ID to the same user:

Kotlin
PostHog.alias("distinct_id")

We strongly recommend reading our docs on alias to best understand how to correctly use this method.

Setting person properties

Besides setting properties during identify, you can set person properties directly with setPersonProperties:

Kotlin
PostHog.setPersonProperties(
userPropertiesToSet = mapOf("plan" to "premium"),
userPropertiesToSetOnce = mapOf("first_seen" to "2025-01-01"),
)

Super properties

Super properties are properties you set once and then send with every subsequent capture call. They're set with PostHog.register, which takes a key and value, and they persist across sessions:

Kotlin
PostHog.register("team_id", 22)

The call above ensures every event sent by the user includes "team_id": 22.

Note: This stores properties against the user's events, not against the user profile itself. To store properties against the person, use identify or setPersonProperties.

To stop sending a super property with events, use unregister:

Kotlin
PostHog.unregister("team_id")

If you're doing this as part of a user logging out, you can instead call PostHog.reset(), which clears all stored super properties and more.

Setting the app language

Events carry $app_language, the language your app displays. On Android 13 and later, the SDK detects it from the app's localeConfig, and on iOS and macOS from the localizations the app bundle declares. Compose Multiplatform resources declare neither, so on iOS and macOS list your languages under CFBundleLocalizations in Info.plist. Android 6 to 12 and the JVM send no $app_language until you set it.

If your app picks its language some other way, such as an in-app setting, call setAppLanguage() with a BCP 47 language tag at startup and whenever the language changes:

Kotlin
PostHog.setAppLanguage("pt-BR")
PostHog.setAppLanguage(null) // back to the detected language

Call setAppLanguage() after PostHog.setup(): on Android and the JVM, a call before setup is dropped. The value is kept in memory only and survives reset(). A $app_language super property set with register() takes precedence. On JavaScript and Wasm, setAppLanguage() does nothing yet, because PostHog.js doesn't support $app_language. To send it there now, call PostHog.register("\$app_language", "pt-BR").

$locale is the device's language. On Android, iOS, and macOS it includes the region, such as de-CH. On the JVM it's a BCP 47 tag that keeps the script, such as zh-Hant-TW.

Feature flags

PostHog's feature flags enable you to safely deploy and roll back new features as well as target specific users and groups with them.

By default, flags are preloaded on setup (preloadFeatureFlags = true). Check whether a flag is enabled:

Kotlin
if (PostHog.isFeatureEnabled("new_dashboard")) {
showNewDashboard()
}

Get the value of a multivariate flag:

Kotlin
when (PostHog.getFeatureFlag("pricing_experiment")) {
"control" -> showOriginalPricing()
"variant_a" -> showNewPricing()
"variant_b" -> showPremiumPricing()
}

Get a detailed result, including the flag's payload:

Kotlin
val result = PostHog.getFeatureFlagResult("new_feature")
if (result != null) {
println("Enabled: ${result.enabled}")
println("Variant: ${result.variant}")
println("Value: ${result.value}") // variant if present, otherwise enabled
// Cast the payload to an expected type
val payload = result.getPayloadAs<Map<String, Any>>()
}

On Android, iOS, macOS and the JVM, payload is null when the flag's payload isn't valid JSON, such as plain text or an empty string. On JavaScript and Wasm, it's the raw string. A flag whose variant is an empty string counts as disabled: isFeatureEnabled() returns false and result.enabled is false, while getFeatureFlag() and result.variant still return "".

Get every evaluated flag at once as a map of FeatureFlagResult:

Kotlin
val allFlags = PostHog.getAllFeatureFlags()

Feature flags are fetched on setup and cached. If a user's properties change (for example, after identify), reload them so they reflect the latest state. The optional callback runs once when the reload finishes and receives a PostHogFeatureFlagsLoaded with the enabled flags (flags), their values (variants), and errorsLoading, which is true when the reload failed and the values are the last known flags:

Kotlin
PostHog.reloadFeatureFlags { loaded ->
if (!loaded.errorsLoading) {
newCheckoutEnabled = "new-checkout" in loaded.flags
}
}

On Android, iOS, macOS, and the JVM, the callback can run on a background thread. Switch to the main thread before you update UI.

To react every time flags load or change, such as at startup, after identify, group, or reset, and after a reload, register a listener with onFeatureFlags(). If flags have already loaded, it also runs with the current values. You can register before setup, and the listener stays active until you unsubscribe. On Android, iOS, and macOS it runs on the main thread:

Kotlin
val subscription = PostHog.onFeatureFlags { loaded ->
showNewCheckout = loaded.variants["new-checkout"] == "test"
}
// Later, stop listening
subscription.unsubscribe()

Setting properties for flag evaluation

If a flag targets a person or group property that you just set, PostHog may not have processed it yet when flags are evaluated. Send the properties with flag requests so the flag uses them right away. They're stored on the device until you reset them, no event is sent, and flags reload afterwards unless you pass reloadFeatureFlags = false:

Kotlin
PostHog.setPersonPropertiesForFlags(mapOf("plan" to "pro"))
PostHog.setGroupPropertiesForFlags("company", mapOf("plan" to "enterprise"))
// Clear them
PostHog.resetPersonPropertiesForFlags()
PostHog.resetGroupPropertiesForFlags("company") // or no argument for every group type

Evaluation contexts

To evaluate only the flags tagged for part of your app, set evaluationContexts in PostHogConfig. PostHog then evaluates the flags with at least one of these evaluation tags, plus flags with no evaluation tags:

Kotlin
PostHogConfig(
projectToken = "<ph_project_token>",
evaluationContexts = listOf("production", "checkout"),
)

Experiments (A/B tests)

Since experiments use feature flags, running one is very similar to the feature flag code above:

Kotlin
if (PostHog.getFeatureFlag("experiment-feature-flag-key") == "variant-name") {
// do something
}

It's also possible to run experiments without using feature flags.

Group analytics

Group analytics lets you associate a user's events with a group (for example, a company, team, or organization). Read the group analytics guide for more information.

Note: This is a paid feature and is not available on the free plan. Learn more on the pricing page.

Associate the current user's events with a group:

Kotlin
// "company" is the group type, "acme_corp" is the group key
PostHog.group(type = "company", key = "acme_corp")

Associate with a group and update that group's properties at the same time:

Kotlin
PostHog.group(
type = "company",
key = "acme_corp",
groupProperties = mapOf(
"name" to "Acme Corporation",
"plan" to "enterprise",
),
)

The name is a special property used in the PostHog UI for the group's name. If you don't specify it, the group key is used instead.

Screen views

Capture a screen view with screen:

Kotlin
PostHog.screen("Home")

You can add properties too:

Kotlin
PostHog.screen(
screenName = "Product Details",
properties = mapOf(
"product_id" to "SKU123",
"category" to "Electronics",
),
)

To automatically capture screen views, set captureScreenViews = true in your config. On Android and iOS, the SDK captures a $screen event for each activity or view controller, so a Compose Multiplatform app with a single one records a single screen. Call screen() for your Compose screens instead. On the web target, it captures $pageview and $pageleave events.

Error tracking

The PostHog Kotlin Multiplatform SDK 0.4.0 and higher can automatically capture unhandled exceptions. First, turn on Enable exception autocapture in your project's Error Tracking settings. This server-side option acts as a kill switch, so the SDK does not automatically capture exceptions when it is disabled.

Then, pass an ErrorTrackingConfig when you initialize PostHog:

Kotlin
import com.posthog.kmp.ErrorTrackingConfig
val config = PostHogConfig(
projectToken = "<ph_project_token>",
errorTracking = ErrorTrackingConfig(
autoCapture = true,
inAppIncludes = listOf("com.example"),
),
)

On Android, iOS, and JVM, this captures unhandled exceptions. On Kotlin/JS and Kotlin/Wasm, it captures unhandled errors and unhandled promise rejections. It does not capture browser console errors.

Capture handled exceptions with their stack traces by calling captureException:

Kotlin
try {
riskyOperation()
} catch (error: Exception) {
PostHog.captureException(
throwable = error,
additionalProperties = mapOf("context" to "checkout_flow"),
)
}

Follow the Kotlin Multiplatform Error Tracking guide for setup and verification. Upload target-specific debug symbols to get readable stack traces from minified and native builds.

Session replay

Session replay is available on Android and iOS. To enable it, turn on "Record user sessions" in your project settings and pass a SessionRecordingConfig:

Kotlin
import com.posthog.kmp.SessionRecordingConfig
PostHog.setup(
config = PostHogConfig(
projectToken = "<ph_project_token>",
sessionRecording = SessionRecordingConfig(
enabled = true,
maskAllTextInputs = true, // mask sensitive text (default)
maskAllImages = true, // mask images (default)
),
),
context = PostHogContext(),
)

Session replay records masked screenshots of your app. Text inputs and images are masked by default, but custom-drawn content such as maps, video or canvas drawing is captured as it appears, so mask it before you ship. posthog-kmp 0.11.0 removed wireframe recording and the screenshot option; remove screenshot from your SessionRecordingConfig when you upgrade. See how mobile replay works.

Compose Multiplatform screens on iOS

On iOS, session replay masks content by finding UIKit views, such as text fields and image views. Compose Multiplatform draws its whole UI into one view, so the SDK can't find the text fields, text, or images inside it, and maskAllTextInputs and maskAllImages don't mask them. Android isn't affected: it masks Compose content.

From posthog-kmp 0.11.0, iOS records Compose Multiplatform screens as they appear, including what users type. Before 0.11.0, iOS didn't record Compose Multiplatform screens at all.

Until the SDK can mask inside Compose on iOS, mask the whole Compose view if it can show sensitive content. Set ph-no-capture as the accessibility identifier of the view controller's view where you create it, usually in your Swift app code:

Swift
func makeUIViewController(context: Context) -> UIViewController {
let controller = MainViewControllerKt.MainViewController()
controller.view.accessibilityIdentifier = "ph-no-capture"
return controller
}

Recordings then show that view as a black block, and you can still see the session's events, network requests and logs. To leave out iOS altogether, enable sessionRecording only on Android.

On Android, enable experimental mask-alignment verification to help preserve screenshot captures during pixel-only redraws, such as continuously animated content:

Kotlin
sessionRecording = SessionRecordingConfig(
enabled = true,
verifyScreenshotMaskAlignment = true,
)

verifyScreenshotMaskAlignment defaults to false and only affects Android. It adds view-hierarchy walks during capture, so evaluate its performance in your app. Windows with a Compose root already use verification regardless of this flag; setting it to false doesn't disable verification for those windows. Other platforms ignore this option.

Opt out of data capture

You can opt users out of data capture in two ways.

Opt users out by default by setting optOut to true in your config:

Kotlin
PostHog.setup(
config = PostHogConfig(projectToken = "<ph_project_token>", optOut = true),
context = PostHogContext(),
)

Or opt a user out (and back in) at runtime:

Kotlin
PostHog.optOut()
PostHog.optIn()

Check whether a user is currently opted out:

Kotlin
if (PostHog.isOptedOut()) {
showConsentBanner()
}

Session management

Access the identifiers PostHog uses for the current session:

Kotlin
val anonymousId = PostHog.getAnonymousId() // before identification
val sessionId = PostHog.getSessionId()
val distinctId = PostHog.getDistinctId()

Flush

You can configure how many events queue before flushing with flushAt. Setting this to 1 will send events immediately and will use more battery. The default is 20.

You can also manually flush the queue to start sending events immediately instead of waiting for the next batch:

Kotlin
PostHog.flush()

Flushing is best-effort and asynchronous – it starts sending queued events in the background but doesn't wait for the request to finish, so it isn't a delivery guarantee.

Reset after logout

To reset the user's ID and anonymous ID, call reset. Usually you'd do this right after the user logs out:

Kotlin
PostHog.reset()

Close

To flush queued events and release resources during a clean shutdown, call close:

Kotlin
PostHog.close()

Debug mode

If you're not seeing the events, feature flags, or session replay behavior you expect, enable debug mode to see verbose logs about what the SDK is doing:

Kotlin
PostHog.setup(
config = PostHogConfig(projectToken = "<ph_project_token>", debug = true),
context = PostHogContext(),
)
// or at runtime
PostHog.setDebug(true)

All configuration options

Pass these to PostHogConfig when calling setup.

OptionTypeDefaultDescription
projectTokenStringRequiredYour PostHog project token.
hostStringHOST_USPostHog instance URL. Use PostHogConfig.HOST_US (https://us.i.posthog.com) or PostHogConfig.HOST_EU (https://eu.i.posthog.com).
debugBooleanfalseEnables verbose SDK logging.
captureApplicationLifecycleEventsBooleantrueCaptures app open/close lifecycle events (mobile).
captureScreenViewsBooleanfalseAutomatically captures $screen events for activities (Android) and view controllers (iOS), and $pageview and $pageleave events on the web.
captureDeepLinksBooleantrueCaptures deep link opens (Android).
sendFeatureFlagEventBooleantrueSends $feature_flag_called when a flag is evaluated.
preloadFeatureFlagsBooleantrueFetches feature flags automatically during setup.
flushAtInt20Number of queued events that triggers a flush.
flushIntervalSecondsInt30Maximum delay before queued events are flushed.
maxQueueSizeInt1000Maximum number of events kept in the queue.
maxBatchSizeInt50Maximum number of events sent in one batch.
optOutBooleanfalseStarts with analytics opted out.
personProfilesPersonProfilesIDENTIFIED_ONLYWhen person profiles are created: IDENTIFIED_ONLY, ALWAYS, or NEVER.
sessionRecordingSessionRecordingConfig?nullEnables and configures session replay (Android and iOS).
autocaptureBooleanfalseEnables automatic event capture where the native platform supports it.
beforeSendList<PostHogBeforeSend>emptyList()Modifies or drops events before the SDK queues them.
errorTrackingErrorTrackingConfig?nullEnables and configures Error Tracking.
capturePushNotificationSubscriptionsBooleantrueRegisters the FCM token at startup when Firebase Messaging is available (Android only).
capturePushNotificationOpenedBooleantrueCaptures push notification opens automatically (Android only).
evaluationContextsList<String>?nullEvaluates only feature flags with one of these evaluation tags, plus untagged flags. null evaluates every flag.
captureAiCompressionPostHogCompression?null (GZIP)How captureAi request bodies are compressed (Android, iOS, macOS, and JVM).
captureAiMaxQueueSizeInt?null (100)Maximum number of captureAi events kept in their own on-disk queue (Android, iOS, macOS, and JVM).
captureAiTimeoutInt?null (60)Seconds a captureAi request can go without network activity before it times out (Android, iOS, macOS, and JVM).
captureAiMaxEventBytesInt?null (8 MiB + 64 KiB)Maximum size of a serialized captureAi event. Can only be lowered (Android, iOS, macOS, and JVM).

Error Tracking options

Pass an ErrorTrackingConfig to PostHogConfig.errorTracking.

OptionTypeDefaultDescription
autoCaptureBooleanfalseAutomatically captures unhandled exceptions.
inAppIncludesList<String>emptyList()Package or bundle prefixes to mark as in-app frames (Android, JVM, and iOS).
ignoredExceptionTypesList<KClass<out Throwable>>emptyList()Exception types that the SDK should not capture (Android, JVM, and iOS).
inAppExcludesList<String>emptyList()Package or bundle prefixes to mark as external frames (iOS and macOS only).
inAppByDefaultBooleantrueMarks unmatched stack frames as in-app frames (iOS and macOS only).

Session recording options

Pass a SessionRecordingConfig to PostHogConfig.sessionRecording. Defaults match the native Android and iOS SDKs.

OptionTypeDefaultDescription
enabledBooleantrueEnables session recording.
maskAllTextInputsBooleantrueMasks all text input values.
maskAllImagesBooleantrueMasks all images.
captureNetworkTelemetryBooleantrueIncludes network requests in the recording.
captureLogsBooleanfalseCaptures console and system logs (iOS and web).
captureLogcatBooleantrueCaptures Android logcat output (Android only).
throttleDelayMsLong1000Minimum delay in milliseconds between replay snapshots (Android and iOS). Replaces the deprecated debouncerDelayMs.
verifyScreenshotMaskAlignmentBooleanfalseExperimental mask-alignment verification for Android screenshots. Adds view-hierarchy walks during capture. Compose-rooted windows always use verification. Ignored on other platforms.

Platform support

PlatformStatusBacked by
Android✅PostHog Android (native)
iOS✅PostHog iOS (native, via SwiftPM)
macOS (Apple silicon)✅PostHog iOS (native, via SwiftPM). Version 0.11.0 and later requires macOS 11 or later.
Web✅PostHog.js
JVM (desktop)✅com.posthog:posthog, the JVM core library the Android SDK is built on

Because the SDK delegates to the native library on each platform, feature availability and behavior follow the underlying SDK. Session replay is available on Android and iOS; the web target inherits PostHog.js behavior.

On the JVM, event capture, identification, feature flags, groups, error tracking, and super properties are all supported. Mobile and browser-only concepts don't apply, so sessionRecording, captureApplicationLifecycleEvents, captureScreenViews, captureDeepLinks, and autocapture are ignored. The JVM also has no standard app-manifest source, so $app_version, $app_build, and $app_namespace person properties aren't set – feature flags targeting those won't match desktop users.

Upgrade to 0.11.0

Version 0.11.0 uses the native Android 4.0, JVM core 7.0, and iOS 4.0 SDKs. The migration guide on GitHub lists every change. These changes apply on Android, iOS, macOS, and the JVM. Of these, only the Session replay and Replay throttling changes reach the web target, as compile errors in common code. The feature flag changes after the list also apply there.

  • Capture endpoint: the SDK sends events to /i/v1/analytics/events. If you use a reverse proxy or you self-host PostHog, make sure that your proxy or instance serves this path, and /i/v1/ai/events if you call captureAi. A reverse proxy must also:
    • Pass these request headers through unchanged: Authorization, PostHog-Sdk-Info, PostHog-Attempt, PostHog-Request-Id, PostHog-Request-Timestamp, Content-Type, Content-Encoding and User-Agent.
    • Return PostHog's response status, body and Retry-After header unchanged. The SDKs read them to decide which events to retry or drop, and drop the events on a 2xx whose body isn't PostHog's.
    • Proxy setups from our guides before 29 October 2026 strip Authorization, so PostHog answers 401 and drops the events. Update yours from the current guide.
  • Retries: until your host serves the path, a 404 is retried about every 30 seconds, and events stay queued only until a full queue evicts them (maxQueueSize, 1000 by default). Other errors that aren't retried, such as 401 or 403, drop the events. Only 307 and 308 redirects to the same origin are followed, 3xx responses are no longer retried, Retry-After is capped at 30 seconds, the wait between failed sends doubles with jitter, and a request carries at most about 5 MiB.
  • Project token: if projectToken is a personal API key (phx_...), the SDK disables itself at setup. Use your project token (phc_...).
  • Super properties: values that you set with register replace the properties that the SDK sets, such as $os_name. A registered $session_id replaces the SDK's session ID, which can detach events from their session replay.
  • Registered $process_person_profile: a $process_person_profile = false set with register(), or a process_person_profile = false set with registerOptions(), now applies to every event except the ones identify(), alias(), group(), and setPersonProperties() send. In 0.10 the SDK replaced it with its own value, so it had no effect. Events after identify() that get it are still linked to the person and billed as identified events, but don't update the person profile. Remove the registered value and use personProfiles instead: the default PersonProfiles.IDENTIFIED_ONLY skips person profiles for anonymous users, and PersonProfiles.NEVER creates none.
  • Build requirements: Xcode 26 or later, and macOS 11 or later for macOS targets. Build your Xcode app once and commit the updated KotlinMultiplatformLinkedPackage, which now pins posthog-ios 4.0.
  • Binary compatibility: recompile any library built against posthog-kmp 0.10. Its Android and JVM bytecode fails at runtime with NoSuchMethodError. Java callers of screen(), identify(), alias(), group(), setPersonProperties(), captureException(), and new CaptureOptions(groups, timestamp) must pass the new eventOptions argument.
  • Other PostHog artifacts: if the same Android or JVM build uses posthog-server, use 2.25.0 or later. If it uses posthog-android-surveys-compose, declare posthog-android 4.0.0 or later alongside it.
  • Person processing in beforeSend: when the SDK doesn't process person profiles for an event, it marks the event with the process_person_profile event option instead of a $process_person_profile = false property. beforeSend reads and changes it in event.options["process_person_profile"], and setting the $process_person_profile property there doesn't turn person processing on. A $process_person_profile that you pass to capture() now applies, even with personProfiles = PersonProfiles.NEVER. To turn person processing on, set the option in beforeSend, pass CaptureOptions(eventOptions = mapOf(PostHogEventOptions.PROCESS_PERSON_PROFILE to true)) to capture(), call identify(), or set personProfiles = PersonProfiles.ALWAYS.
  • Event options: $process_person_profile, $cookieless_mode, $ignore_sent_at, and $product_tour_id have event options that replace them. The properties still work.
  • Event changes: events with an empty name, or whose distinct ID beforeSend blanks, are dropped. $feature_flag_called for a missing flag leaves out $feature_flag_response – filter on is not set. Application Installed, Application Updated, and Application Opened no longer have version and build on iOS and macOS – use $app_version and $app_build. $locale is now the device's preferred language and region on Android, iOS, and macOS, such as de-CH, and a BCP 47 tag that keeps the script on the JVM, such as zh-Hant-TW. PostHog drops events whose name or distinct ID is over 200 bytes. On iOS and macOS, a null value inside a nested map is left out. On Android and the JVM, a null list element is sent as null at its position instead of being removed. $sdk_debug_replay_capture_mode is always screenshot. Android's Deep Link Opened leaves out query parameters whose name starts with $. Refer to the migration guide for the full list.
  • Session replay: recordings are always masked screenshots, and the screenshot option is gone. On Android, Compose screens, including Compose Multiplatform UI, are now recorded, which can count against your replay quota. On iOS, Compose Multiplatform screens are now recorded too, but their text fields, text and images aren't masked, so mask the Compose view first. Refer to Compose Multiplatform screens on iOS. Because screenshot is gone, SessionRecordingConfig positional arguments and destructuring shift, so use named arguments. Refer to Session replay.
  • Replay throttling: use throttleDelayMs instead of the deprecated debouncerDelayMs. The constructor still accepts debouncerDelayMs, but copy(debouncerDelayMs = ...) no longer compiles.
  • Payloads: FeatureFlagResult.payload is null for a payload that isn't valid JSON, instead of the raw string. On Android and the JVM, a JSON null payload is null instead of the string "null". On the web target it's still the raw string.

These feature flag changes also apply to the web target:

  • reloadFeatureFlags callback: the callback now receives a PostHogFeatureFlagsLoaded. A lambda that ignores it still compiles, but a function reference or a () -> Unit value needs the parameter. Before setup, the callback runs right away with no flags and errorsLoading = true.
  • Empty variants: a flag whose variant is an empty string is disabled on every platform and is left out of $active_feature_flags.

FAQ

Which platforms does the KMP SDK support?

Android, iOS, macOS (Apple silicon), web, and JVM (desktop). The SDK is designed for Kotlin Multiplatform projects – including Compose Multiplatform – that share business logic across these targets.

Is this different from the Android SDK?

Yes. The Android SDK is for native Android apps. The KMP SDK is for shared Kotlin code targeting multiple platforms, and it wraps the native Android, iOS, and web SDKs so you can call one common API from commonMain.

Why don't I see surveys or logs?

The KMP wrapper currently exposes event capture, identification, feature flags, group analytics, screen tracking, session replay, and error tracking. Surveys and logs aren't wrapped yet. If you'd like logs support, upvote the logs feature request on GitHub – subscribing to the issue is the best way to follow along.

Still have questions?

Was this page useful?