Electron
Note: This SDK is currently in beta. APIs and behavior can change in minor version releases. Test your packaged app on each operating system and Electron version that you ship.
The PostHog Electron SDK (@posthog/electron) captures data from your Electron desktop app. It supports Electron 41 and later.
One PostHog client runs in the main process. This client owns identity, consent, sessions, storage, and network requests. Renderer windows and utility processes send their calls to the main process through a secure bridge. Thus, all windows and processes share one identity and one session.
The SDK supports:
- Custom events and screen views
- User identification, aliases, and person properties
- Group analytics
- Feature flags and experiments
- Application lifecycle events
- Error tracking for JavaScript exceptions
- DOM autocapture in renderer windows (opt-in)
Installation
Install @posthog/electron with your package manager:
Keep electron as a development dependency of your app. Do not bundle Electron into your app's JavaScript.
The package has a different entry point for each process type:
| Entry point | Use it in |
|---|---|
@posthog/electron/main | The main process |
@posthog/electron/preload | The preload script of a BrowserWindow |
@posthog/electron/preload/helper | Your own preload script, if you already have one |
@posthog/electron/renderer | Renderer windows |
@posthog/electron/react | Renderer windows that use React 18 or later |
@posthog/electron/utility | Utility processes that you start with utilityProcess.fork() |
There is no root export. Always import from the entry point for the process.
Main process
Initialize PostHog one time in the main process, before you create windows. Then register each window that can send data to PostHog:
Set projectToken to your project token, not a personal API key. Set host to https://us.i.posthog.com or https://eu.i.posthog.com, for your region. You can also use a reverse proxy URL. The SDK does not follow redirects, so use the final URL, including the path of your proxy.
Important: If you use native ESM in the main process, do not use top-level
await app.whenReady(). Use a callback or an async function that you do not await at module scope. If you do, Electron cannot finish loading the entry point.
Window registration and security
Only registered windows can use the bridge. The SDK accepts calls only from the main frame of the window, and only at the URLs that you supply in allowedUrls. The URLs must match exactly, but the SDK ignores URL fragments. The SDK checks the URL again after each navigation.
- Register each window that you trust, which includes windows in custom partitions.
- Do not register windows that show remote content or content that you do not trust.
- Keep
contextIsolationenabled. Do not expose raw IPC APIs to the page.
Use your own preload script
If your window already has a preload script, do not replace it. Add the PostHog bridge to your script:
A sandboxed preload script cannot load npm packages at runtime. Bundle the helper into your preload script, and keep only electron as an external module.
Renderer
Bundle your renderer code with Vite, esbuild, or a different browser bundler. Then initialize the renderer client:
init() gets the current state from the main process. If you call init() more than one time, you get the same client, and only the options from the first call apply.
capture(), screen(), and captureException() do not return a value, and they do not throw. They queue the event and return immediately. If the SDK cannot queue the event, it reports the error through onError.
Other methods that change data, such as identify(), reset(), and optIn(), return promises. Await identity, reset, and consent changes before you capture events that depend on them. The SDK runs commands in the order that you call them.
Capturing events
You can capture events in the main process, in a renderer, or in a utility process:
To capture a screen view, use screen(). This captures a $screen event:
The SDK adds the $electron_process property to each event. Its value is main, renderer, or utility.
Super properties
Super properties are properties that the SDK adds to each event that you capture. Use register() to set them:
Identifying users
Identify users to link their events to a person profile. For more information, see identifying users.
The app has one identity for all windows and processes, not one identity for each window.
When a user logs out, call reset() before you identify a different user:
If a renderer sends a command for the previous user after an identity change, the SDK rejects the command. A rejected capture is dropped and reported through onError. Do not capture it again for the new user.
To link the current distinct ID to an alias, use alias():
To set person properties without a change to the identity, use setPersonProperties():
To read the current IDs, use getDistinctId(), getAnonymousId(), and getSessionId().
Group analytics
Group analytics let you associate events with a group, such as a team or a company. Read the group analytics docs for more information.
Note: This is a paid feature and is not available on the open-source or free cloud plan. Learn more on the pricing page.
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.
The main process loads feature flags, keeps them in a cache, and shares them with each registered window and utility process. The flag methods read the cache synchronously. They do not fetch flags.
posthog.ready() in main and init() in a renderer load the cached flags from the previous run. They do not wait for the first flag request. On a fresh install without bootstrap, the cache is empty, so a single flag read returns undefined. To try to get the latest flag values before you use them, await reloadFeatureFlags() or use onStateChange(). If the request fails, reloadFeatureFlags() keeps the cached values:
If a flag is not known, getFeatureFlag() returns false when the cache has at least one flag. It returns undefined when the cache is empty, which includes when a project has no flags for the user. To set a fallback value for unknown flags, use isFeatureEnabled("flag-key", { defaultValue: false }).
getFeatureFlag(), isFeatureEnabled(), and getFeatureFlagResult() send a $feature_flag_called event. The SDK sends only one event for each flag value. To stop the event, use { sendFeatureFlagEvent: false }. Payload reads and getAllFeatureFlags() do not send the event.
To request the latest flag values, call reloadFeatureFlags(). If the request fails, the SDK keeps the cached values:
Listen for changes
In a renderer or a utility process, use onStateChange() to get updates to identity, consent, or flags. It returns a function that removes the listener:
Properties for flag evaluation
To set person or group properties for flag evaluation only, without a profile event:
By default, these methods reload flags. To keep the current flag values, set the second argument to false, then call reloadFeatureFlags() when you are ready.
To clear the properties, use resetPersonPropertiesForFlags() and resetGroupPropertiesForFlags().
Experiments (A/B tests)
Experiments use feature flags, so you can use the same methods. For more information, see the experiments docs.
Error tracking
To capture an error that your code handles, use captureException() in main, in a renderer, or in a utility process:
The SDK does not capture errors automatically by default. To capture uncaught errors, enable enableExceptionAutocapture in each process where you need it:
In the main process:
In a renderer:
In the renderer, the SDK captures error and unhandledrejection events. It does not capture errors when a resource does not load.
In the main process, the SDK captures uncaught exceptions. By default, it does not capture unhandled promise rejections, because Electron only shows a warning for them. To capture them, set captureUnhandledRejections: true. This option also needs enableExceptionAutocapture: true:
This option adds a process.on("unhandledRejection") listener until shutdown. While the listener is installed, Node.js does not show the UnhandledPromiseRejectionWarning and does not set process.exitCode to 1. If your app uses process.exitCode to find failed runs, set it yourself.
You can also capture unhandled rejections in your own handler instead. Your listener has the same effect on the warning and on process.exitCode:
The SDK does not replace your error handlers, and it does not stop your app from exiting. It cannot guarantee that it sends an error before the app exits.
Note: The SDK captures JavaScript errors only. It does not capture native crashes, and it does not symbolicate native stack traces. It does not capture uncaught errors in utility processes.
Autocapture
The SDK can capture clicks, changes, and form submissions in renderer windows. Autocapture is off by default. To enable it, set autocapture when you initialize each renderer:
Set autocapture: true to use the default settings. The configuration object accepts these options:
| Option | Description |
|---|---|
maskAllText | Removes element text. Default is false. |
maskAllElementAttributes | Removes element attributes. Default is false. |
disableCaptureUrlHashes | Removes the URL fragment. Default is false. |
url_allowlist, url_ignorelist | Arrays of strings or regular expressions. |
dom_event_allowlist | Any of "click", "change", and "submit". |
element_allowlist | Any of "a", "button", "form", "input", "select", "textarea", and "label". |
css_selector_allowlist, css_selector_ignorelist | Arrays of CSS selectors. |
element_attribute_ignorelist | An array of attribute names. |
Autocapture does not collect input values or clipboard contents. Elements with the ph-no-capture class are always ignored. If you set css_selector_ignorelist, it replaces the default list (.ph-no-autocapture and [data-ph-no-autocapture]). Include these selectors in your list if you need them.
Text and attributes can contain personal data. Use masking, ignore lists, and before_send to apply your privacy policy.
Autocapture also obeys the autocapture setting in your project settings:
- On the first start, autocapture stays off until the SDK gets this setting. If the request fails, autocapture stays off.
- After that, the SDK saves the last setting that it got. If a later request fails, the SDK uses the saved setting.
- If the saved setting turns autocapture off, autocapture stays off.
- If you set
disableRemoteConfig: truein the main process, the SDK does not request the setting. Autocapture runs unless a saved setting turns it off.
If the user opts out, autocapture always stops.
React
For React 18 and later, use @posthog/electron/react. Pass a renderer client that you already initialized to PostHogProvider. Do not pass a posthog-js client or a project token.
The hooks return undefined while flags are not available. Handle this value in your components.
useFeatureFlagEnabled and useFeatureFlagVariantKey send a $feature_flag_called event. useFeatureFlagPayload does not.
When PostHogProvider unmounts, it does not dispose the client. Call posthog.dispose() after you unmount the provider.
Utility processes
You can send data from a utility process that you own and trust. In the main process, register the child process immediately after you start it:
In the utility process, initialize the client:
The utility client has the same methods as the renderer client. It sends all calls to the main process. To get errors for failed calls, such as a capture over the rate limit, pass an onError function to init(). Each call waits a maximum of 10 seconds for the main process. If a call times out, do not retry it automatically, because the main process can have accepted it.
Important: A registered utility process can change the identity and consent of the app. Do not register a process that runs code that you do not trust.
Lifecycle events
By default, the SDK captures these events:
| Event | When |
|---|---|
Application Installed | The first time that the SDK starts in the app |
Application Updated | The app version or appBuild is different from the previous start |
Application Opened | The app starts, or a registered window gets focus after the app was in the background |
Application Backgrounded | No registered window has focus |
To disable these events, set captureAppLifecycleEvents: false.
A new session starts each time the app starts. A session also ends after 30 minutes without activity, or after 24 hours.
Opt out of data capture
The SDK captures events by default. To require consent first, set defaultOptIn: false. Then call optIn() when the user gives consent. The SDK saves the user's choice, and a saved choice takes priority over defaultOptIn:
When the user opts out, the SDK does not capture new events. The SDK still sends events that it captured before the user opted out.
Opt-out applies to events only. The SDK can still request feature flags, which sends the distinct ID to PostHog. If your app must not send any data before the user gives consent, call init() only after consent.
Flush and shutdown
To send queued events immediately, call flush(). The promise rejects if the SDK cannot send the events:
When the app quits, the SDK tries to send queued events, but it does not delay the quit.
To give the SDK more time to send events, call shutdown() with a timeout in milliseconds. Call it only when your app is sure to quit, after other cleanup that uses PostHog:
After shutdown(), you cannot use the client. If the timeout ends first, the SDK keeps the unsent events on disk and sends them the next time that the app starts.
If a user closes all windows, the SDK continues to run. Thus, a tray app can continue to capture events.
Storage
The SDK stores identity, consent, flags, and queued events in this file:
The file is not encrypted. Do not put secrets or personal API keys in events or in your app.
Only one process can write to the storage of a project at a time. If a second process uses the same storage, it stays inactive and reports an error through onError. To run a separate instance, set a different storageDirectory.
Network
The SDK sends requests through an isolated Electron session (posthog-electron). The requests do not include cookies or HTTP credentials. The SDK does not follow redirects.
To use a forward proxy, call setProxy() on this session after the app is ready and before you call init(). The SDK can send a feature flag request immediately after init(), and setProxy() does not change requests that already started:
Note: The SDK does not support forward proxies that require authentication.
If a request fails because of a network error or a 407, 408, 429, or 5xx response, the SDK keeps the events and tries again later. PostHog can receive the same event more than one time.
Configuration
These are the options for init() in the main process:
| Option | Description |
|---|---|
projectToken | Your project token. Required. |
host | The URL of your PostHog instance or reverse proxy. |
onError | A function that the SDK calls when an error occurs, for example a network or storage error. |
defaultOptIn | Set to false to require optIn() before the SDK captures events. Applies only when the user has no saved choice. Default is true. |
disabled | Set to true to disable the SDK. |
captureAppLifecycleEvents | Captures lifecycle events. Default is true. |
enableExceptionAutocapture | Captures uncaught errors in the main process. Default is false. |
captureUnhandledRejections | Captures unhandled promise rejections in the main process. Needs enableExceptionAutocapture: true. Default is false. See error tracking. |
appBuild | Your app's build number. The SDK uses it to find app updates. |
personProfiles | Default is "identified_only", which creates person profiles only for identified users. Set to "always" to also create them for anonymous users, or "never" to disable them. |
before_send | A function that can change or drop events before the SDK queues them. |
bootstrap | Initial distinct ID and feature flag values. |
preloadFeatureFlags | Loads flags when the SDK starts. |
disableRemoteFeatureFlags | Stops the SDK from loading flags from PostHog. |
disableRemoteConfig | Stops the SDK from loading the project configuration. |
disableGeoip | Adds $geoip_disable to captured events, so PostHog does not add GeoIP properties to them. It does not apply to feature flag requests. |
flushAt, flushInterval | The number of events and the time in milliseconds before the SDK sends events. Set flushInterval to 0 to disable scheduled sends. |
maxBatchSize | The maximum number of events in one request. |
maxQueueSize | The maximum number of queued events. Default is 1000. |
maxStorageBytes | The maximum size of the storage file. Default is 5 MiB. |
maxQueueAgeMs | The time after which the SDK discards queued events. Default is 7 days. |
storageDirectory | The directory for the storage file. Default is <app.getPath("userData")>/posthog. |
sessionExpirationTimeSeconds | The time without activity after which a session ends. Default is 30 minutes. |
The options for init() in a renderer are autocapture, enableExceptionAutocapture, and onError.
Limitations
- In the main process, the SDK does not capture unhandled promise rejections by default. To capture them, set
captureUnhandledRejections: true.





