PostHog Node.js SDK

SDK Version: 5.7.0

|

PostHog

Initialization methods

PostHogpublic

Initialize a new PostHog client instance.

Parameters

NameType
apiKeystring

Your PostHog project API key

options?PostHogOptions

Configuration options for the client

Examples

JavaScript
// Basic initialization
const client = new PostHogBackendClient(
'your-api-key',
{ host: 'https://app.posthog.com' }
)

Returns

Type
any

debugpublic

Enable or disable debug logging.

Parameters

NameType
enabled?boolean

Whether to enable debug logging

Examples

JavaScript
// Enable debug logging
client.debug(true)

Returns

Type
void

getLibraryVersionpublic

Get the library version from package.json.

Examples

JavaScript
// Get version
const version = client.getLibraryVersion()
console.log(`Using PostHog SDK version: ${version}`)

Returns

Type
string

getPersistedPropertypublic

Get a persisted property value from memory storage.

Parameters

NameType
keyPostHogPersistedProperty

The property key to retrieve

Examples

JavaScript
// Get user ID
const userId = client.getPersistedProperty('userId')

Returns

Type
Union ofany
undefined

setPersistedPropertypublic

Set a persisted property value in memory storage.

Parameters

NameType
keyPostHogPersistedProperty

The property key to set

valueany | null

The value to store (null to remove)

Examples

JavaScript
// Set user ID
client.setPersistedProperty('userId', 'user_123')

Returns

Type
void

Capture methods

capturepublic

Capture an event manually.

Parameters

NameType
propsEventMessage

The event properties

Examples

JavaScript
// Basic capture
client.capture({
distinctId: 'user_123',
event: 'button_clicked',
properties: { button_color: 'red' }
})

Returns

Type
void

captureImmediatepublic

Capture an event immediately (synchronously).

Parameters

NameType
propsEventMessage

The event properties

Examples

JavaScript
// Basic immediate capture
await 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

NameType
errorunknown

The error to capture

distinctId?string

Optional user distinct ID

additionalProperties?Record<string | number, any>

Optional additional properties to include

Examples

JavaScript
// Capture an error with user ID
try {
// Some risky operation
riskyOperation()
} catch (error) {
client.captureException(error, 'user_123')
}

Returns

Type
void

captureExceptionImmediatepublic

Capture an error exception as an event immediately (synchronously).

Parameters

NameType
errorunknown

The error to capture

distinctId?string

Optional user distinct ID

additionalProperties?Record<string | number, any>

Optional additional properties to include

Examples

JavaScript
// Capture an error immediately with user ID
try {
// Some risky operation
riskyOperation()
} 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

NameType
distinctIdstring

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

JavaScript
// Get all flags for a user
const 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

NameType
distinctIdstring

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

JavaScript
// Get all flags and payloads for a user
const result = await client.getAllFlagsAndPayloads('user_123')
console.log('Flags:', result.featureFlags)
console.log('Payloads:', result.featureFlagPayloads)

getFeatureFlagpublic

Get the value of a feature flag for a specific user.

Parameters

NameType
keystring

The feature flag key

distinctIdstring

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

JavaScript
// Basic feature flag check
const 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 ofPromise<FeatureFlagValue
undefined>

getFeatureFlagPayloadpublic

Get the payload for a feature flag.

Parameters

NameType
keystring

The feature flag key

distinctIdstring

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

JavaScript
// Get payload for a feature flag
const payload = await client.getFeatureFlagPayload('flag-key', 'user_123')
if (payload) {
console.log('Flag payload:', payload)
}

Returns

Type
Union ofPromise<JsonType
undefined>

getRemoteConfigPayloadpublic

Get the remote config payload for a feature flag.

Parameters

NameType
flagKeystring

The feature flag key

Examples

JavaScript
// Get remote config payload
const payload = await client.getRemoteConfigPayload('flag-key')
if (payload) {
console.log('Remote config payload:', payload)
}

Returns

Type
Union ofPromise<JsonType
undefined>

isFeatureEnabledpublic

Check if a feature flag is enabled for a specific user.

Parameters

NameType
keystring

The feature flag key

distinctIdstring

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

JavaScript
// Basic feature flag check
const isEnabled = await client.isFeatureEnabled('new-feature', 'user_123')
if (isEnabled) {
// Feature is enabled
console.log('New feature is active')
} else {
// Feature is disabled
console.log('New feature is not active')
}

Returns

Type
Union ofPromise<boolean
undefined>

isLocalEvaluationReadypublic

Check if local evaluation of feature flags is ready.

Examples

JavaScript
// Check if ready
if (client.isLocalEvaluationReady()) {
// Local evaluation is ready, can evaluate flags locally
const flag = await client.getFeatureFlag('flag-key', 'user_123')
} else {
// Local evaluation not ready, will use remote evaluation
const flag = await client.getFeatureFlag('flag-key', 'user_123')
}

Returns

Type
boolean

reloadFeatureFlagspublic

Reload feature flag definitions from the server for local evaluation.

Examples

JavaScript
// Force reload of feature flags
await client.reloadFeatureFlags()
console.log('Feature flags reloaded')

Returns

Type
Promise<void>

waitForLocalEvaluationReadypublic

Wait for local evaluation of feature flags to be ready.

Parameters

NameType
timeoutMs?number

Timeout in milliseconds (default: 30000)

Examples

JavaScript
// Wait for local evaluation
const 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

NameType
data{ distinctId: string; alias: string; disableGeoip?: boolean; }

The alias data containing distinctId and alias

Examples

JavaScript
// Link an anonymous user to an identified user
client.alias({
distinctId: 'anonymous_123',
alias: 'user_456'
})

Returns

Type
void

aliasImmediatepublic

Create an alias to link two distinct IDs together immediately (synchronously).

Parameters

NameType
data{ distinctId: string; alias: string; disableGeoip?: boolean; }

The alias data containing distinctId and alias

Examples

JavaScript
// Link an anonymous user to an identified user immediately
await client.aliasImmediate({
distinctId: 'anonymous_123',
alias: 'user_456'
})

Returns

Type
Promise<void>

getCustomUserAgentpublic

Get the custom user agent string for this client.

Examples

JavaScript
// Get user agent
const userAgent = client.getCustomUserAgent()
// Returns: "posthog-node/5.7.0"

Returns

Type
string

groupIdentifypublic

Create or update a group and its properties.

Parameters

NameType
{ groupType, groupKey, properties, distinctId, disableGeoip }GroupIdentifyMessage

Examples

JavaScript
// Create a company group
client.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

NameType
{ distinctId, properties, disableGeoip }IdentifyMessage

Examples

JavaScript
// Basic identify with properties
client.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

NameType
{ distinctId, properties, disableGeoip }IdentifyMessage

Examples

JavaScript
// Basic immediate identify
await 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

JavaScript
// Disable client
await client.disable()
// Client is now disabled and will not capture events

Returns

Type
Promise<void>

enablepublic

Enable the PostHog client (opt-in).

Examples

JavaScript
// Enable client
await client.enable()
// Client is now enabled and will capture events

Returns

Type
Promise<void>

Other methods

getLibraryIdpublic

Examples

JavaScript
// Generated example for getLibraryId
posthog.getLibraryId();

Returns

Type
string

addPendingPromisepublic

Parameters

NameType
promisePromise<T>

Examples

JavaScript
// Generated example for addPendingPromise
posthog.addPendingPromise();

Returns

Type
Promise<T>

aliasStatelesspublic

Parameters

NameType
aliasstring
distinctIdstring
properties?PostHogEventProperties
options?PostHogCaptureOptions

Examples

JavaScript
// Generated example for aliasStateless
posthog.aliasStateless();

Returns

Type
void

aliasStatelessImmediatepublic

Parameters

NameType
aliasstring
distinctIdstring
properties?PostHogEventProperties
options?PostHogCaptureOptions

Examples

JavaScript
// Generated example for aliasStatelessImmediate
posthog.aliasStatelessImmediate();

Returns

Type
Promise<void>

captureStatelesspublic

Parameters

NameType
distinctIdstring
eventstring
properties?PostHogEventProperties
options?PostHogCaptureOptions

Examples

JavaScript
// Generated example for captureStateless
posthog.captureStateless();

Returns

Type
void

captureStatelessImmediatepublic

Parameters

NameType
distinctIdstring
eventstring
properties?PostHogEventProperties
options?PostHogCaptureOptions

Examples

JavaScript
// Generated example for captureStatelessImmediate
posthog.captureStatelessImmediate();

Returns

Type
Promise<void>

enqueuepublic

  • ** QUEUEING AND FLUSHING *

Parameters

NameType
typestring
_messageany
options?PostHogCaptureOptions

Examples

JavaScript
// Generated example for enqueue
posthog.enqueue();

Returns

Type
void

fetchpublic

Parameters

NameType
urlstring
optionsPostHogFetchOptions

Examples

JavaScript
// Generated example for fetch
posthog.fetch();

Returns

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

JavaScript
posthog.flush().then(() => { console.log('Flush complete') }).catch((err) => { console.error('Flush failed', err) })

Returns

Type
Promise<void>

getCommonEventPropertiespublic

Examples

JavaScript
// Generated example for getCommonEventProperties
posthog.getCommonEventProperties();

getCustomHeaderspublic

Examples

JavaScript
// Generated example for getCustomHeaders
posthog.getCustomHeaders();

Returns

Type
{ [key: string]: string; }

getFeatureFlagDetailsStatelesspublic

Parameters

NameType
distinctIdstring
groups?Record<string, string | number>
personProperties?Record<string, string>
groupProperties?Record<string, Record<string, string>>
disableGeoip?boolean
flagKeysToEvaluate?string[]

Examples

JavaScript
// Generated example for getFeatureFlagDetailsStateless
posthog.getFeatureFlagDetailsStateless();

Returns

Type
Union ofPromise<PostHogFeatureFlagDetails
undefined>

getFeatureFlagDetailStatelesspublic

Parameters

NameType
keystring
distinctIdstring
groups?Record<string, string>
personProperties?Record<string, string>
groupProperties?Record<string, Record<string, string>>
disableGeoip?boolean

Examples

JavaScript
// Generated example for getFeatureFlagDetailStateless
posthog.getFeatureFlagDetailStateless();

Returns

Type
Union ofPromise<{ response: FeatureFlagDetail
undefined; requestId: string
undefined; }
undefined>

getFeatureFlagPayloadsStatelesspublic

Parameters

NameType
distinctIdstring
groups?Record<string, string>
personProperties?Record<string, string>
groupProperties?Record<string, Record<string, string>>
disableGeoip?boolean
flagKeysToEvaluate?string[]

Examples

JavaScript
// Generated example for getFeatureFlagPayloadsStateless
posthog.getFeatureFlagPayloadsStateless();

Returns

Type
Union ofPromise<PostHogFlagsResponse['featureFlagPayloads']
undefined>

getFeatureFlagPayloadStatelesspublic

Parameters

NameType
keystring
distinctIdstring
groups?Record<string, string>
personProperties?Record<string, string>
groupProperties?Record<string, Record<string, string>>
disableGeoip?boolean

Examples

JavaScript
// Generated example for getFeatureFlagPayloadStateless
posthog.getFeatureFlagPayloadStateless();

Returns

Type
Union ofPromise<JsonType
undefined>

getFeatureFlagsAndPayloadsStatelesspublic

Parameters

NameType
distinctIdstring
groups?Record<string, string | number>
personProperties?Record<string, string>
groupProperties?Record<string, Record<string, string>>
disableGeoip?boolean
flagKeysToEvaluate?string[]

Examples

JavaScript
// Generated example for getFeatureFlagsAndPayloadsStateless
posthog.getFeatureFlagsAndPayloadsStateless();

Returns

Type
Union ofPromise<{ flags: PostHogFlagsResponse['featureFlags']
undefined; payloads: PostHogFlagsResponse['featureFlagPayloads']
undefined; requestId: PostHogFlagsResponse['requestId']
undefined; }>

getFeatureFlagsStatelesspublic

Parameters

NameType
distinctIdstring
groups?Record<string, string | number>
personProperties?Record<string, string>
groupProperties?Record<string, Record<string, string>>
disableGeoip?boolean
flagKeysToEvaluate?string[]

Examples

JavaScript
// Generated example for getFeatureFlagsStateless
posthog.getFeatureFlagsStateless();

Returns

Type
Union ofPromise<{ flags: PostHogFlagsResponse['featureFlags']
undefined; payloads: PostHogFlagsResponse['featureFlagPayloads']
undefined; requestId: PostHogFlagsResponse['requestId']
undefined; }>

getFeatureFlagStatelesspublic

Parameters

NameType
keystring
distinctIdstring
groups?Record<string, string>
personProperties?Record<string, string>
groupProperties?Record<string, Record<string, string>>
disableGeoip?boolean

Examples

JavaScript
// Generated example for getFeatureFlagStateless
posthog.getFeatureFlagStateless();

Returns

Type
Union ofPromise<{ response: FeatureFlagValue
undefined; requestId: string
undefined; }>

getFlagspublic

  • ** FEATURE FLAGS *

Parameters

NameType
distinctIdstring
groups?Record<string, string | number>
personProperties?Record<string, string>
groupProperties?Record<string, Record<string, string>>
extraPayload?Record<string, any>

Examples

JavaScript
// Generated example for getFlags
posthog.getFlags();

Returns

Type
Union ofPromise<PostHogFlagsResponse
undefined>

getRemoteConfigpublic

Examples

JavaScript
// Generated example for getRemoteConfig
posthog.getRemoteConfig();

Returns

Type
Union ofPromise<PostHogRemoteConfig
undefined>

getSurveysStatelesspublic

  • ** SURVEYS *

Examples

JavaScript
// Generated example for getSurveysStateless
posthog.getSurveysStateless();

Returns

Type
Promise<SurveyResponse['surveys']>

groupIdentifyStatelesspublic

  • ** GROUPS *

Parameters

NameType
groupTypestring
groupKeystring | number
groupProperties?PostHogEventProperties
options?PostHogCaptureOptions
distinctId?string
eventProperties?PostHogEventProperties

Examples

JavaScript
// Generated example for groupIdentifyStateless
posthog.groupIdentifyStateless();

Returns

Type
void

identifyStatelesspublic

  • ** TRACKING *

Parameters

NameType
distinctIdstring
properties?PostHogEventProperties
options?PostHogCaptureOptions

Examples

JavaScript
// Generated example for identifyStateless
posthog.identifyStateless();

Returns

Type
void

identifyStatelessImmediatepublic

Parameters

NameType
distinctIdstring
properties?PostHogEventProperties
options?PostHogCaptureOptions

Examples

JavaScript
// Generated example for identifyStatelessImmediate
posthog.identifyStatelessImmediate();

Returns

Type
Promise<void>

logMsgIfDebugpublic

Parameters

NameType
fn() => void

Examples

JavaScript
// Generated example for logMsgIfDebug
posthog.logMsgIfDebug();

Returns

Type
void

onpublic

Parameters

NameType
eventstring
cb(...args: any[]) => void

Examples

JavaScript
// Generated example for on
posthog.on();

Returns

Type
() => void

optInpublic

Examples

JavaScript
// Generated example for optIn
posthog.optIn();

Returns

Type
Promise<void>

optOutpublic

Examples

JavaScript
// Generated example for optOut
posthog.optOut();

Returns

Type
Promise<void>

registerpublic

Parameters

NameType
propertiesPostHogEventProperties

Examples

JavaScript
// Generated example for register
posthog.register();

Returns

Type
Promise<void>

sendImmediatepublic

Parameters

NameType
typestring
_messageany
options?PostHogCaptureOptions

Examples

JavaScript
// Generated example for sendImmediate
posthog.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

NameType
shutdownTimeoutMs?number

Examples

JavaScript
// Generated example for shutdown
posthog.shutdown();

Returns

Type
Promise<void>

unregisterpublic

Parameters

NameType
propertystring

Examples

JavaScript
// Generated example for unregister
posthog.unregister();

Returns

Type
Promise<void>

wrappublic

Parameters

NameType
fn() => void

Examples

JavaScript
// Generated example for wrap
posthog.wrap();

Returns

Type
void

Community questions

Was this page useful?