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:

Terminal
npm install @posthog/electron

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 pointUse it in
@posthog/electron/mainThe main process
@posthog/electron/preloadThe preload script of a BrowserWindow
@posthog/electron/preload/helperYour own preload script, if you already have one
@posthog/electron/rendererRenderer windows
@posthog/electron/reactRenderer windows that use React 18 or later
@posthog/electron/utilityUtility 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:

JavaScript
import { app, BrowserWindow } from "electron"
import { createRequire } from "node:module"
import { pathToFileURL } from "node:url"
import { init } from "@posthog/electron/main"
const require = createRequire(import.meta.url)
const posthog = init({
projectToken: "<ph_project_token>",
host: "https://us.i.posthog.com",
onError: (error) => console.error("[PostHog]", error),
})
app.whenReady().then(async () => {
await posthog.ready()
const page = "/absolute/path/to/index.html"
const window = new BrowserWindow({
webPreferences: {
preload: require.resolve("@posthog/electron/preload"),
sandbox: true,
contextIsolation: true,
nodeIntegration: false,
},
})
posthog.registerWindow(window, { allowedUrls: [pathToFileURL(page).href] })
await window.loadFile(page)
posthog.capture("application_ready")
})

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 contextIsolation enabled. 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:

JavaScript
import { exposePostHogBridge } from "@posthog/electron/preload/helper"
exposePostHogBridge()
// The rest of your preload 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:

JavaScript
import { init } from "@posthog/electron/renderer"
const posthog = await init()
posthog.capture("button_clicked", { button: "save" })

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:

JavaScript
posthog.capture("user_signed_up", {
login_type: "email",
is_free_trial: true,
})

To capture a screen view, use screen(). This captures a $screen event:

JavaScript
posthog.screen("Settings", { section: "billing" })

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:

JavaScript
await posthog.register({ workspace: "primary" })

Identifying users

Identify users to link their events to a person profile. For more information, see identifying users.

JavaScript
await posthog.identify("distinct_id_from_your_database", {
email: "max@hedgehogmail.com",
name: "Max Hedgehog",
})

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:

JavaScript
await posthog.reset()

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():

JavaScript
await posthog.alias("alias_id")

To set person properties without a change to the identity, use setPersonProperties():

JavaScript
await posthog.setPersonProperties(
{ plan: "pro" }, // $set
{ first_seen_version: "1.0.0" } // $set_once
)

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.

JavaScript
await posthog.group("company", "company_id_in_your_db", {
name: "Awesome Inc.",
})

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:

JavaScript
const posthog = await init()
await posthog.reloadFeatureFlags()
if (posthog.isFeatureEnabled("flag-key")) {
// Do something
}
JavaScript
// A boolean flag
if (posthog.isFeatureEnabled("flag-key")) {
// Do something
}
// A multivariate flag
if (posthog.getFeatureFlag("flag-key") === "variant-key") {
// Do something
}
// The full result, which includes the variant and the payload
const result = posthog.getFeatureFlagResult("flag-key")
// Only the payload
const payload = posthog.getFeatureFlagPayload("flag-key")
// All flags
const flags = posthog.getAllFeatureFlags()

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:

JavaScript
await posthog.reloadFeatureFlags()

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:

JavaScript
const unsubscribe = posthog.onStateChange((state) => {
console.log(state.featureFlags)
})

Properties for flag evaluation

To set person or group properties for flag evaluation only, without a profile event:

JavaScript
await posthog.setPersonPropertiesForFlags({ plan: "pro" })
await posthog.setGroupPropertiesForFlags({ company: { plan: "enterprise" } })

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:

JavaScript
try {
// Code that can throw
} catch (error) {
posthog.captureException(error, { context: "save" })
}

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:

JavaScript
import { init } from "@posthog/electron/main"
const posthog = init({
projectToken: "<ph_project_token>",
enableExceptionAutocapture: true,
})

In a renderer:

JavaScript
import { init } from "@posthog/electron/renderer"
const posthog = await init({ enableExceptionAutocapture: true })

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:

JavaScript
import { init } from "@posthog/electron/main"
const posthog = init({
projectToken: "<ph_project_token>",
enableExceptionAutocapture: true,
captureUnhandledRejections: 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:

JavaScript
const onUnhandledRejection = (reason) => {
posthog.captureException(reason)
}
process.on("unhandledRejection", onUnhandledRejection)
// When your app shuts down
process.removeListener("unhandledRejection", onUnhandledRejection)

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:

JavaScript
import { init } from "@posthog/electron/renderer"
const posthog = await init({
autocapture: {
maskAllText: true,
maskAllElementAttributes: true,
},
})

Set autocapture: true to use the default settings. The configuration object accepts these options:

OptionDescription
maskAllTextRemoves element text. Default is false.
maskAllElementAttributesRemoves element attributes. Default is false.
disableCaptureUrlHashesRemoves the URL fragment. Default is false.
url_allowlist, url_ignorelistArrays of strings or regular expressions.
dom_event_allowlistAny of "click", "change", and "submit".
element_allowlistAny of "a", "button", "form", "input", "select", "textarea", and "label".
css_selector_allowlist, css_selector_ignorelistArrays of CSS selectors.
element_attribute_ignorelistAn 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: true in 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.

JSX
import { createRoot } from "react-dom/client"
import { init } from "@posthog/electron/renderer"
import {
PostHogProvider,
usePostHog,
useFeatureFlagEnabled,
useFeatureFlagVariantKey,
useFeatureFlagPayload,
} from "@posthog/electron/react"
const posthog = await init()
function App() {
const client = usePostHog()
const enabled = useFeatureFlagEnabled("new-ui")
const variant = useFeatureFlagVariantKey("new-ui")
const payload = useFeatureFlagPayload("new-ui")
return (
<button
disabled={!enabled}
onClick={() => client.capture("new_ui_clicked", { variant: variant ?? null })}
>
Try the new UI
</button>
)
}
createRoot(document.getElementById("root")).render(
<PostHogProvider client={posthog}>
<App />
</PostHogProvider>
)

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:

JavaScript
import { utilityProcess } from "electron"
const child = utilityProcess.fork("/absolute/path/to/utility.cjs")
const unregister = posthog.registerUtilityProcess(child)
// Later, to disconnect the child from PostHog without stopping it:
unregister()

In the utility process, initialize the client:

JavaScript
const { init } = require("@posthog/electron/utility")
async function run() {
const posthog = await init()
posthog.capture("background_work_completed", { task: "thumbnail" })
await posthog.flush()
}
run().catch(console.error)

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:

EventWhen
Application InstalledThe first time that the SDK starts in the app
Application UpdatedThe app version or appBuild is different from the previous start
Application OpenedThe app starts, or a registered window gets focus after the app was in the background
Application BackgroundedNo 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:

JavaScript
const posthog = init({
projectToken: "<ph_project_token>",
defaultOptIn: false,
})
// Later, in main or in a renderer
await posthog.optIn()
await posthog.optOut()
posthog.hasOptedOutCapturing()

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:

JavaScript
await posthog.flush()

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:

JavaScript
await posthog.shutdown(2000)

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:

<app.getPath("userData")>/posthog/<hash>/state.json

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:

JavaScript
import { app, session } from "electron"
import { init } from "@posthog/electron/main"
app.whenReady().then(async () => {
await session.fromPartition("posthog-electron").setProxy({ proxyRules: "http://proxy.example.com:8080" })
const posthog = init({ projectToken: "<ph_project_token>" })
})

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:

OptionDescription
projectTokenYour project token. Required.
hostThe URL of your PostHog instance or reverse proxy.
onErrorA function that the SDK calls when an error occurs, for example a network or storage error.
defaultOptInSet to false to require optIn() before the SDK captures events. Applies only when the user has no saved choice. Default is true.
disabledSet to true to disable the SDK.
captureAppLifecycleEventsCaptures lifecycle events. Default is true.
enableExceptionAutocaptureCaptures uncaught errors in the main process. Default is false.
captureUnhandledRejectionsCaptures unhandled promise rejections in the main process. Needs enableExceptionAutocapture: true. Default is false. See error tracking.
appBuildYour app's build number. The SDK uses it to find app updates.
personProfilesDefault 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_sendA function that can change or drop events before the SDK queues them.
bootstrapInitial distinct ID and feature flag values.
preloadFeatureFlagsLoads flags when the SDK starts.
disableRemoteFeatureFlagsStops the SDK from loading flags from PostHog.
disableRemoteConfigStops the SDK from loading the project configuration.
disableGeoipAdds $geoip_disable to captured events, so PostHog does not add GeoIP properties to them. It does not apply to feature flag requests.
flushAt, flushIntervalThe number of events and the time in milliseconds before the SDK sends events. Set flushInterval to 0 to disable scheduled sends.
maxBatchSizeThe maximum number of events in one request.
maxQueueSizeThe maximum number of queued events. Default is 1000.
maxStorageBytesThe maximum size of the storage file. Default is 5 MiB.
maxQueueAgeMsThe time after which the SDK discards queued events. Default is 7 days.
storageDirectoryThe directory for the storage file. Default is <app.getPath("userData")>/posthog.
sessionExpirationTimeSecondsThe 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

Still have questions?

Was this page useful?