PostHog Node.js SDK
SDK Version: 5.7.0
|PostHog
Initialization methods
PostHogpublic
Initialize a new PostHog client instance.
Parameters
| Name | Type |
|---|---|
apiKey | string |
Your PostHog project API key | |
options? | PostHogOptions |
Configuration options for the client | |
Examples
// Basic initializationconst client = new PostHogBackendClient('your-api-key',{ host: 'https://app.posthog.com' })
Returns
| Type |
|---|
any |
debugpublic
Enable or disable debug logging.
Parameters
| Name | Type |
|---|---|
enabled? | boolean |
Whether to enable debug logging | |
Examples
// Enable debug loggingclient.debug(true)
Returns
| Type |
|---|
void |
getLibraryVersionpublic
Get the library version from package.json.
Examples
// Get versionconst version = client.getLibraryVersion()console.log(`Using PostHog SDK version: ${version}`)
Returns
| Type |
|---|
string |
getPersistedPropertypublic
Get a persisted property value from memory storage.
Parameters
| Name | Type |
|---|---|
key | PostHogPersistedProperty |
The property key to retrieve | |
Examples
// Get user IDconst userId = client.getPersistedProperty('userId')
Returns
| Type | |
|---|---|
| Union of | any |
undefined |
setPersistedPropertypublic
Set a persisted property value in memory storage.
Parameters
| Name | Type |
|---|---|
key | PostHogPersistedProperty |
The property key to set | |
value | any | null |
The value to store (null to remove) | |
Examples
// Set user IDclient.setPersistedProperty('userId', 'user_123')
Returns
| Type |
|---|
void |
Capture methods
Examples
// Basic captureclient.capture({distinctId: 'user_123',event: 'button_clicked',properties: { button_color: 'red' }})
Returns
| Type |
|---|
void |
captureImmediatepublic
Capture an event immediately (synchronously).
Parameters
| Name | Type |
|---|---|
props | EventMessage |
The event properties | |
Examples
// Basic immediate captureawait client.captureImmediate({distinctId: 'user_123',event: 'button_clicked',properties: { button_color: 'red' }})
Returns
| Type |
|---|
Promise<void> |
Error tracking methods
captureExceptionpublic
Capture an error exception as an event.
Parameters
| Name | Type |
|---|---|
error | unknown |
The error to capture | |
distinctId? | string |
Optional user distinct ID | |
additionalProperties? | Record<string | number, any> |
Optional additional properties to include | |
Examples
// Capture an error with user IDtry {// Some risky operationriskyOperation()} catch (error) {client.captureException(error, 'user_123')}
Returns
| Type |
|---|
void |
captureExceptionImmediatepublic
Capture an error exception as an event immediately (synchronously).
Parameters
| Name | Type |
|---|---|
error | unknown |
The error to capture | |
distinctId? | string |
Optional user distinct ID | |
additionalProperties? | Record<string | number, any> |
Optional additional properties to include | |
Examples
// Capture an error immediately with user IDtry {// Some risky operationriskyOperation()} catch (error) {await client.captureExceptionImmediate(error, 'user_123')}
Returns
| Type |
|---|
Promise<void> |
Feature flags methods
getAllFlagspublic
Get all feature flag values for a specific user.
Parameters
| Name | Type |
|---|---|
distinctId | string |
The user's distinct ID | |
options? | {
groups?: Record<string, string>;
personProperties?: Record<string, string>;
groupProperties?: Record<string, Record<string, string>>;
onlyEvaluateLocally?: boolean;
disableGeoip?: boolean;
flagKeys?: string[];
} |
Optional configuration for flag evaluation | |
Examples
// Get all flags for a userconst allFlags = await client.getAllFlags('user_123')console.log('User flags:', allFlags)// Output: { 'flag-1': 'variant-a', 'flag-2': false, 'flag-3': 'variant-b' }
Returns
| Type |
|---|
Promise<Record<string, FeatureFlagValue>> |
getAllFlagsAndPayloadspublic
Get all feature flag values and payloads for a specific user.
Parameters
| Name | Type |
|---|---|
distinctId | string |
The user's distinct ID | |
options? | {
groups?: Record<string, string>;
personProperties?: Record<string, string>;
groupProperties?: Record<string, Record<string, string>>;
onlyEvaluateLocally?: boolean;
disableGeoip?: boolean;
flagKeys?: string[];
} |
Optional configuration for flag evaluation | |
Examples
// Get all flags and payloads for a userconst result = await client.getAllFlagsAndPayloads('user_123')console.log('Flags:', result.featureFlags)console.log('Payloads:', result.featureFlagPayloads)
Returns
| Type |
|---|
Promise<PostHogFlagsAndPayloadsResponse> |
getFeatureFlagpublic
Get the value of a feature flag for a specific user.
Parameters
| Name | Type |
|---|---|
key | string |
The feature flag key | |
distinctId | string |
The user's distinct ID | |
options? | {
groups?: Record<string, string>;
personProperties?: Record<string, string>;
groupProperties?: Record<string, Record<string, string>>;
onlyEvaluateLocally?: boolean;
sendFeatureFlagEvents?: boolean;
disableGeoip?: boolean;
} |
Optional configuration for flag evaluation | |
Examples
// Basic feature flag checkconst flagValue = await client.getFeatureFlag('new-feature', 'user_123')if (flagValue === 'variant-a') {// Show variant A} else if (flagValue === 'variant-b') {// Show variant B} else {// Flag is disabled or not found}
Returns
| Type | |
|---|---|
| Union of | Promise<FeatureFlagValue |
undefined> |
getFeatureFlagPayloadpublic
Get the payload for a feature flag.
Parameters
| Name | Type |
|---|---|
key | string |
The feature flag key | |
distinctId | string |
The user's distinct ID | |
matchValue? | FeatureFlagValue |
Optional match value to get payload for | |
options? | {
groups?: Record<string, string>;
personProperties?: Record<string, string>;
groupProperties?: Record<string, Record<string, string>>;
onlyEvaluateLocally?: boolean;
sendFeatureFlagEvents?: boolean;
disableGeoip?: boolean;
} |
Optional configuration for flag evaluation | |
Examples
// Get payload for a feature flagconst payload = await client.getFeatureFlagPayload('flag-key', 'user_123')if (payload) {console.log('Flag payload:', payload)}
Returns
| Type | |
|---|---|
| Union of | Promise<JsonType |
undefined> |
getRemoteConfigPayloadpublic
Get the remote config payload for a feature flag.
Parameters
| Name | Type |
|---|---|
flagKey | string |
The feature flag key | |
Examples
// Get remote config payloadconst payload = await client.getRemoteConfigPayload('flag-key')if (payload) {console.log('Remote config payload:', payload)}
Returns
| Type | |
|---|---|
| Union of | Promise<JsonType |
undefined> |
isFeatureEnabledpublic
Check if a feature flag is enabled for a specific user.
Parameters
| Name | Type |
|---|---|
key | string |
The feature flag key | |
distinctId | string |
The user's distinct ID | |
options? | {
groups?: Record<string, string>;
personProperties?: Record<string, string>;
groupProperties?: Record<string, Record<string, string>>;
onlyEvaluateLocally?: boolean;
sendFeatureFlagEvents?: boolean;
disableGeoip?: boolean;
} |
Optional configuration for flag evaluation | |
Examples
// Basic feature flag checkconst isEnabled = await client.isFeatureEnabled('new-feature', 'user_123')if (isEnabled) {// Feature is enabledconsole.log('New feature is active')} else {// Feature is disabledconsole.log('New feature is not active')}
Returns
| Type | |
|---|---|
| Union of | Promise<boolean |
undefined> |
isLocalEvaluationReadypublic
Check if local evaluation of feature flags is ready.
Examples
// Check if readyif (client.isLocalEvaluationReady()) {// Local evaluation is ready, can evaluate flags locallyconst flag = await client.getFeatureFlag('flag-key', 'user_123')} else {// Local evaluation not ready, will use remote evaluationconst flag = await client.getFeatureFlag('flag-key', 'user_123')}
Returns
| Type |
|---|
boolean |
reloadFeatureFlagspublic
Reload feature flag definitions from the server for local evaluation.
Examples
// Force reload of feature flagsawait client.reloadFeatureFlags()console.log('Feature flags reloaded')
Returns
| Type |
|---|
Promise<void> |
waitForLocalEvaluationReadypublic
Wait for local evaluation of feature flags to be ready.
Parameters
| Name | Type |
|---|---|
timeoutMs? | number |
Timeout in milliseconds (default: 30000) | |
Examples
// Wait for local evaluationconst isReady = await client.waitForLocalEvaluationReady()if (isReady) {console.log('Local evaluation is ready')} else {console.log('Local evaluation timed out')}
Returns
| Type |
|---|
Promise<boolean> |
Identification methods
aliaspublic
Create an alias to link two distinct IDs together.
Parameters
| Name | Type |
|---|---|
data | {
distinctId: string;
alias: string;
disableGeoip?: boolean;
} |
The alias data containing distinctId and alias | |
Examples
// Link an anonymous user to an identified userclient.alias({distinctId: 'anonymous_123',alias: 'user_456'})
Returns
| Type |
|---|
void |
aliasImmediatepublic
Create an alias to link two distinct IDs together immediately (synchronously).
Parameters
| Name | Type |
|---|---|
data | {
distinctId: string;
alias: string;
disableGeoip?: boolean;
} |
The alias data containing distinctId and alias | |
Examples
// Link an anonymous user to an identified user immediatelyawait client.aliasImmediate({distinctId: 'anonymous_123',alias: 'user_456'})
Returns
| Type |
|---|
Promise<void> |
getCustomUserAgentpublic
Get the custom user agent string for this client.
Examples
// Get user agentconst userAgent = client.getCustomUserAgent()// Returns: "posthog-node/5.7.0"
Returns
| Type |
|---|
string |
groupIdentifypublic
Create or update a group and its properties.
Parameters
| Name | Type |
|---|---|
{ groupType, groupKey, properties, distinctId, disableGeoip } | GroupIdentifyMessage |
Examples
// Create a company groupclient.groupIdentify({groupType: 'company',groupKey: 'acme-corp',properties: {name: 'Acme Corporation',industry: 'Technology',employee_count: 500},distinctId: 'user_123'})
Returns
| Type |
|---|
void |
identifypublic
Identify a user and set their properties.
Parameters
| Name | Type |
|---|---|
{ distinctId, properties, disableGeoip } | IdentifyMessage |
Examples
// Basic identify with propertiesclient.identify({distinctId: 'user_123',properties: {name: 'John Doe',email: 'john@example.com',plan: 'premium'}})
Returns
| Type |
|---|
void |
identifyImmediatepublic
Identify a user and set their properties immediately (synchronously).
Parameters
| Name | Type |
|---|---|
{ distinctId, properties, disableGeoip } | IdentifyMessage |
Examples
// Basic immediate identifyawait client.identifyImmediate({distinctId: 'user_123',properties: {name: 'John Doe',email: 'john@example.com'}})
Returns
| Type |
|---|
Promise<void> |
Privacy methods
disablepublic
Disable the PostHog client (opt-out).
Examples
// Disable clientawait client.disable()// Client is now disabled and will not capture events
Returns
| Type |
|---|
Promise<void> |
enablepublic
Enable the PostHog client (opt-in).
Examples
// Enable clientawait client.enable()// Client is now enabled and will capture events
Returns
| Type |
|---|
Promise<void> |
Other methods
getLibraryIdpublic
Examples
// Generated example for getLibraryIdposthog.getLibraryId();
Returns
| Type |
|---|
string |
addPendingPromisepublic
Parameters
| Name | Type |
|---|---|
promise | Promise<T> |
Examples
// Generated example for addPendingPromiseposthog.addPendingPromise();
Returns
| Type |
|---|
Promise<T> |
aliasStatelesspublic
Parameters
| Name | Type |
|---|---|
alias | string |
distinctId | string |
properties? | PostHogEventProperties |
options? | PostHogCaptureOptions |
Examples
// Generated example for aliasStatelessposthog.aliasStateless();
Returns
| Type |
|---|
void |
aliasStatelessImmediatepublic
Parameters
| Name | Type |
|---|---|
alias | string |
distinctId | string |
properties? | PostHogEventProperties |
options? | PostHogCaptureOptions |
Examples
// Generated example for aliasStatelessImmediateposthog.aliasStatelessImmediate();
Returns
| Type |
|---|
Promise<void> |
captureStatelesspublic
Parameters
| Name | Type |
|---|---|
distinctId | string |
event | string |
properties? | PostHogEventProperties |
options? | PostHogCaptureOptions |
Examples
// Generated example for captureStatelessposthog.captureStateless();
Returns
| Type |
|---|
void |
captureStatelessImmediatepublic
Parameters
| Name | Type |
|---|---|
distinctId | string |
event | string |
properties? | PostHogEventProperties |
options? | PostHogCaptureOptions |
Examples
// Generated example for captureStatelessImmediateposthog.captureStatelessImmediate();
Returns
| Type |
|---|
Promise<void> |
enqueuepublic
- ** QUEUEING AND FLUSHING *
Parameters
| Name | Type |
|---|---|
type | string |
_message | any |
options? | PostHogCaptureOptions |
Examples
// Generated example for enqueueposthog.enqueue();
Returns
| Type |
|---|
void |
fetchpublic
Parameters
| Name | Type |
|---|---|
url | string |
options | PostHogFetchOptions |
Examples
// Generated example for fetchposthog.fetch();
Returns
| Type |
|---|
Promise<PostHogFetchResponse> |
flushpublic
Flushes the queue
This function will return a promise that will resolve when the flush is complete, or reject if there was an error (for example if the server or network is down).
If there is already a flush in progress, this function will wait for that flush to complete.
It's recommended to do error handling in the callback of the promise.
Examples
posthog.flush().then(() => { console.log('Flush complete') }).catch((err) => { console.error('Flush failed', err) })
Returns
| Type |
|---|
Promise<void> |
getCommonEventPropertiespublic
Examples
// Generated example for getCommonEventPropertiesposthog.getCommonEventProperties();
Returns
getCustomHeaderspublic
Examples
// Generated example for getCustomHeadersposthog.getCustomHeaders();
Returns
| Type |
|---|
{
[key: string]: string;
} |
getFeatureFlagDetailsStatelesspublic
Parameters
| Name | Type |
|---|---|
distinctId | string |
groups? | Record<string, string | number> |
personProperties? | Record<string, string> |
groupProperties? | Record<string, Record<string, string>> |
disableGeoip? | boolean |
flagKeysToEvaluate? | string[] |
Examples
// Generated example for getFeatureFlagDetailsStatelessposthog.getFeatureFlagDetailsStateless();
Returns
| Type | |
|---|---|
| Union of | Promise<PostHogFeatureFlagDetails |
undefined> |
getFeatureFlagDetailStatelesspublic
Parameters
| Name | Type |
|---|---|
key | string |
distinctId | string |
groups? | Record<string, string> |
personProperties? | Record<string, string> |
groupProperties? | Record<string, Record<string, string>> |
disableGeoip? | boolean |
Examples
// Generated example for getFeatureFlagDetailStatelessposthog.getFeatureFlagDetailStateless();
Returns
| Type | |
|---|---|
| Union of | Promise<{
response: FeatureFlagDetail |
undefined;
requestId: string | |
undefined;
} | |
undefined> |
getFeatureFlagPayloadsStatelesspublic
Parameters
| Name | Type |
|---|---|
distinctId | string |
groups? | Record<string, string> |
personProperties? | Record<string, string> |
groupProperties? | Record<string, Record<string, string>> |
disableGeoip? | boolean |
flagKeysToEvaluate? | string[] |
Examples
// Generated example for getFeatureFlagPayloadsStatelessposthog.getFeatureFlagPayloadsStateless();
Returns
| Type | |
|---|---|
| Union of | Promise<PostHogFlagsResponse['featureFlagPayloads'] |
undefined> |
getFeatureFlagPayloadStatelesspublic
Parameters
| Name | Type |
|---|---|
key | string |
distinctId | string |
groups? | Record<string, string> |
personProperties? | Record<string, string> |
groupProperties? | Record<string, Record<string, string>> |
disableGeoip? | boolean |
Examples
// Generated example for getFeatureFlagPayloadStatelessposthog.getFeatureFlagPayloadStateless();
Returns
| Type | |
|---|---|
| Union of | Promise<JsonType |
undefined> |
getFeatureFlagsAndPayloadsStatelesspublic
Parameters
| Name | Type |
|---|---|
distinctId | string |
groups? | Record<string, string | number> |
personProperties? | Record<string, string> |
groupProperties? | Record<string, Record<string, string>> |
disableGeoip? | boolean |
flagKeysToEvaluate? | string[] |
Examples
// Generated example for getFeatureFlagsAndPayloadsStatelessposthog.getFeatureFlagsAndPayloadsStateless();
Returns
| Type | |
|---|---|
| Union of | Promise<{
flags: PostHogFlagsResponse['featureFlags'] |
undefined;
payloads: PostHogFlagsResponse['featureFlagPayloads'] | |
undefined;
requestId: PostHogFlagsResponse['requestId'] | |
undefined;
}> |
getFeatureFlagsStatelesspublic
Parameters
| Name | Type |
|---|---|
distinctId | string |
groups? | Record<string, string | number> |
personProperties? | Record<string, string> |
groupProperties? | Record<string, Record<string, string>> |
disableGeoip? | boolean |
flagKeysToEvaluate? | string[] |
Examples
// Generated example for getFeatureFlagsStatelessposthog.getFeatureFlagsStateless();
Returns
| Type | |
|---|---|
| Union of | Promise<{
flags: PostHogFlagsResponse['featureFlags'] |
undefined;
payloads: PostHogFlagsResponse['featureFlagPayloads'] | |
undefined;
requestId: PostHogFlagsResponse['requestId'] | |
undefined;
}> |
getFeatureFlagStatelesspublic
Parameters
| Name | Type |
|---|---|
key | string |
distinctId | string |
groups? | Record<string, string> |
personProperties? | Record<string, string> |
groupProperties? | Record<string, Record<string, string>> |
disableGeoip? | boolean |
Examples
// Generated example for getFeatureFlagStatelessposthog.getFeatureFlagStateless();
Returns
| Type | |
|---|---|
| Union of | Promise<{
response: FeatureFlagValue |
undefined;
requestId: string | |
undefined;
}> |
getFlagspublic
- ** FEATURE FLAGS *
Parameters
| Name | Type |
|---|---|
distinctId | string |
groups? | Record<string, string | number> |
personProperties? | Record<string, string> |
groupProperties? | Record<string, Record<string, string>> |
extraPayload? | Record<string, any> |
Examples
// Generated example for getFlagsposthog.getFlags();
Returns
| Type | |
|---|---|
| Union of | Promise<PostHogFlagsResponse |
undefined> |
getRemoteConfigpublic
Examples
// Generated example for getRemoteConfigposthog.getRemoteConfig();
Returns
| Type | |
|---|---|
| Union of | Promise<PostHogRemoteConfig |
undefined> |
getSurveysStatelesspublic
- ** SURVEYS *
Examples
// Generated example for getSurveysStatelessposthog.getSurveysStateless();
Returns
| Type |
|---|
Promise<SurveyResponse['surveys']> |
groupIdentifyStatelesspublic
- ** GROUPS *
Parameters
| Name | Type |
|---|---|
groupType | string |
groupKey | string | number |
groupProperties? | PostHogEventProperties |
options? | PostHogCaptureOptions |
distinctId? | string |
eventProperties? | PostHogEventProperties |
Examples
// Generated example for groupIdentifyStatelessposthog.groupIdentifyStateless();
Returns
| Type |
|---|
void |
identifyStatelesspublic
- ** TRACKING *
Parameters
| Name | Type |
|---|---|
distinctId | string |
properties? | PostHogEventProperties |
options? | PostHogCaptureOptions |
Examples
// Generated example for identifyStatelessposthog.identifyStateless();
Returns
| Type |
|---|
void |
identifyStatelessImmediatepublic
Parameters
| Name | Type |
|---|---|
distinctId | string |
properties? | PostHogEventProperties |
options? | PostHogCaptureOptions |
Examples
// Generated example for identifyStatelessImmediateposthog.identifyStatelessImmediate();
Returns
| Type |
|---|
Promise<void> |
logMsgIfDebugpublic
Parameters
| Name | Type |
|---|---|
fn | () => void |
Examples
// Generated example for logMsgIfDebugposthog.logMsgIfDebug();
Returns
| Type |
|---|
void |
onpublic
Parameters
| Name | Type |
|---|---|
event | string |
cb | (...args: any[]) => void |
Examples
// Generated example for onposthog.on();
Returns
| Type |
|---|
() => void |
optInpublic
Examples
// Generated example for optInposthog.optIn();
Returns
| Type |
|---|
Promise<void> |
optOutpublic
Examples
// Generated example for optOutposthog.optOut();
Returns
| Type |
|---|
Promise<void> |
registerpublic
Parameters
| Name | Type |
|---|---|
properties | PostHogEventProperties |
Examples
// Generated example for registerposthog.register();
Returns
| Type |
|---|
Promise<void> |
sendImmediatepublic
Parameters
| Name | Type |
|---|---|
type | string |
_message | any |
options? | PostHogCaptureOptions |
Examples
// Generated example for sendImmediateposthog.sendImmediate();
Returns
| Type |
|---|
Promise<void> |
shutdownpublic
Call shutdown() once before the node process exits, so ensure that all events have been sent and all promises have resolved. Do not use this function if you intend to keep using this PostHog instance after calling it.
Parameters
| Name | Type |
|---|---|
shutdownTimeoutMs? | number |
Examples
// Generated example for shutdownposthog.shutdown();
Returns
| Type |
|---|
Promise<void> |
unregisterpublic
Parameters
| Name | Type |
|---|---|
property | string |
Examples
// Generated example for unregisterposthog.unregister();
Returns
| Type |
|---|
Promise<void> |
wrappublic
Parameters
| Name | Type |
|---|---|
fn | () => void |
Examples
// Generated example for wrapposthog.wrap();
Returns
| Type |
|---|
void |