PostHog Node.js SDK
SDK Version: 5.7.0
|PostHog
Initialization methods
PostHog
public
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 |
debug
public
Enable or disable debug logging.
Parameters
Name | Type |
---|---|
enabled? | boolean |
Whether to enable debug logging |
Examples
// Enable debug loggingclient.debug(true)
Returns
Type |
---|
void |
getLibraryVersion
public
Get the library version from package.json.
Examples
// Get versionconst version = client.getLibraryVersion()console.log(`Using PostHog SDK version: ${version}`)
Returns
Type |
---|
string |
getPersistedProperty
public
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 |
setPersistedProperty
public
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 |
captureImmediate
public
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
captureException
public
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 |
captureExceptionImmediate
public
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
getAllFlags
public
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>> |
getAllFlagsAndPayloads
public
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> |
getFeatureFlag
public
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> |
getFeatureFlagPayload
public
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> |
getRemoteConfigPayload
public
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> |
isFeatureEnabled
public
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> |
isLocalEvaluationReady
public
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 |
reloadFeatureFlags
public
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> |
waitForLocalEvaluationReady
public
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
alias
public
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 |
aliasImmediate
public
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> |
getCustomUserAgent
public
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 |
groupIdentify
public
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 |
identify
public
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 |
identifyImmediate
public
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
disable
public
Disable the PostHog client (opt-out).
Examples
// Disable clientawait client.disable()// Client is now disabled and will not capture events
Returns
Type |
---|
Promise<void> |
enable
public
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
getLibraryId
public
Examples
// Generated example for getLibraryIdposthog.getLibraryId();
Returns
Type |
---|
string |
addPendingPromise
public
Parameters
Name | Type |
---|---|
promise | Promise<T> |
Examples
// Generated example for addPendingPromiseposthog.addPendingPromise();
Returns
Type |
---|
Promise<T> |
aliasStateless
public
Parameters
Name | Type |
---|---|
alias | string |
distinctId | string |
properties? | PostHogEventProperties |
options? | PostHogCaptureOptions |
Examples
// Generated example for aliasStatelessposthog.aliasStateless();
Returns
Type |
---|
void |
aliasStatelessImmediate
public
Parameters
Name | Type |
---|---|
alias | string |
distinctId | string |
properties? | PostHogEventProperties |
options? | PostHogCaptureOptions |
Examples
// Generated example for aliasStatelessImmediateposthog.aliasStatelessImmediate();
Returns
Type |
---|
Promise<void> |
captureStateless
public
Parameters
Name | Type |
---|---|
distinctId | string |
event | string |
properties? | PostHogEventProperties |
options? | PostHogCaptureOptions |
Examples
// Generated example for captureStatelessposthog.captureStateless();
Returns
Type |
---|
void |
captureStatelessImmediate
public
Parameters
Name | Type |
---|---|
distinctId | string |
event | string |
properties? | PostHogEventProperties |
options? | PostHogCaptureOptions |
Examples
// Generated example for captureStatelessImmediateposthog.captureStatelessImmediate();
Returns
Type |
---|
Promise<void> |
enqueue
public
- ** QUEUEING AND FLUSHING *
Parameters
Name | Type |
---|---|
type | string |
_message | any |
options? | PostHogCaptureOptions |
Examples
// Generated example for enqueueposthog.enqueue();
Returns
Type |
---|
void |
fetch
public
Parameters
Name | Type |
---|---|
url | string |
options | PostHogFetchOptions |
Examples
// Generated example for fetchposthog.fetch();
Returns
Type |
---|
Promise<PostHogFetchResponse> |
flush
public
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> |
getCommonEventProperties
public
Examples
// Generated example for getCommonEventPropertiesposthog.getCommonEventProperties();
Returns
getCustomHeaders
public
Examples
// Generated example for getCustomHeadersposthog.getCustomHeaders();
Returns
Type |
---|
{
[key: string]: string;
} |
getFeatureFlagDetailsStateless
public
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> |
getFeatureFlagDetailStateless
public
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> |
getFeatureFlagPayloadsStateless
public
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> |
getFeatureFlagPayloadStateless
public
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> |
getFeatureFlagsAndPayloadsStateless
public
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;
}> |
getFeatureFlagsStateless
public
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;
}> |
getFeatureFlagStateless
public
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;
}> |
getFlags
public
- ** 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> |
getRemoteConfig
public
Examples
// Generated example for getRemoteConfigposthog.getRemoteConfig();
Returns
Type | |
---|---|
Union of | Promise<PostHogRemoteConfig |
undefined> |
getSurveysStateless
public
- ** SURVEYS *
Examples
// Generated example for getSurveysStatelessposthog.getSurveysStateless();
Returns
Type |
---|
Promise<SurveyResponse['surveys']> |
groupIdentifyStateless
public
- ** 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 |
identifyStateless
public
- ** TRACKING *
Parameters
Name | Type |
---|---|
distinctId | string |
properties? | PostHogEventProperties |
options? | PostHogCaptureOptions |
Examples
// Generated example for identifyStatelessposthog.identifyStateless();
Returns
Type |
---|
void |
identifyStatelessImmediate
public
Parameters
Name | Type |
---|---|
distinctId | string |
properties? | PostHogEventProperties |
options? | PostHogCaptureOptions |
Examples
// Generated example for identifyStatelessImmediateposthog.identifyStatelessImmediate();
Returns
Type |
---|
Promise<void> |
logMsgIfDebug
public
Parameters
Name | Type |
---|---|
fn | () => void |
Examples
// Generated example for logMsgIfDebugposthog.logMsgIfDebug();
Returns
Type |
---|
void |
on
public
Parameters
Name | Type |
---|---|
event | string |
cb | (...args: any[]) => void |
Examples
// Generated example for onposthog.on();
Returns
Type |
---|
() => void |
optIn
public
Examples
// Generated example for optInposthog.optIn();
Returns
Type |
---|
Promise<void> |
optOut
public
Examples
// Generated example for optOutposthog.optOut();
Returns
Type |
---|
Promise<void> |
register
public
Parameters
Name | Type |
---|---|
properties | PostHogEventProperties |
Examples
// Generated example for registerposthog.register();
Returns
Type |
---|
Promise<void> |
sendImmediate
public
Parameters
Name | Type |
---|---|
type | string |
_message | any |
options? | PostHogCaptureOptions |
Examples
// Generated example for sendImmediateposthog.sendImmediate();
Returns
Type |
---|
Promise<void> |
shutdown
public
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> |
unregister
public
Parameters
Name | Type |
---|---|
property | string |
Examples
// Generated example for unregisterposthog.unregister();
Returns
Type |
---|
Promise<void> |
wrap
public
Parameters
Name | Type |
---|---|
fn | () => void |
Examples
// Generated example for wrapposthog.wrap();
Returns
Type |
---|
void |