Chapter 47 · Instrument Integration
Subchapter 47.54
references/posthog-node.mdMarkdown26 KBView on GitHub
SDK Version: 5.36.2
PostHog Node.js SDK allows you to capture events and send them to PostHog from your Node.js applications.
Release Tag: public
string// Generated example for getLibraryId
posthog.getLibraryId();Release Tag: public
Set context without a callback wrapper.
Uses AsyncLocalStorage.enterWith() to attach context to the current async execution context. The context lives until that async context ends.
Must be called in the same async scope that makes PostHog calls. Calling this outside a request-scoped async context will leak context across unrelated work. Prefer withContext() when you can wrap code in a callback — it creates an isolated scope that cleans up automatically.
data (Partial<ContextData>) - Context data to apply (distinctId, sessionId, properties)options? (ContextOptions) - Context options (fresh: true to start with clean context instead of inheriting)void// Generated example for enterContext
posthog.enterContext();Release Tag: public
Promise<void>// Generated example for flush
posthog.flush();Release Tag: public
props (EventMessage)Promise<{ distinctId: string; event: string; properties: PostHogEventProperties; options: PostHogCaptureOptions; }>// Generated example for prepareEventMessage
posthog.prepareEventMessage();Release Tag: public
url (string)options (PostHogFetchOptions)Promise<PostHogFetchResponse>// Generated example for fetch
posthog.fetch();Release Tag: public
Promise<SurveyResponse['surveys']>// Generated example for getSurveysStateless
posthog.getSurveysStateless();Release Tag: public
event (string)cb ((...args: any[]) => void)() => void// Generated example for on
posthog.on();Release Tag: public
Promise<void>// Generated example for optIn
posthog.optIn();Release Tag: public
Promise<void>// Generated example for optOut
posthog.optOut();Release Tag: public
properties (PostHogEventProperties)Promise<void>// Generated example for register
posthog.register();Release Tag: public
property (string)Promise<void>// Generated example for unregister
posthog.unregister();Release Tag: public
Initialize a new PostHog client instance.
apiKey (string) - Your PostHog project API keyoptions? (PostHogOptions) - Configuration options for the clientany// Basic initialization
const client = new PostHogBackendClient(
'your-api-key',
{ host: 'https://app.posthog.com' }
)// With personal API key
const client = new PostHogBackendClient(
'your-api-key',
{
host: 'https://app.posthog.com',
personalApiKey: 'your-personal-api-key'
}
)Release Tag: public
Enable or disable debug logging.
enabled? (boolean) - Whether to enable debug loggingvoid// Enable debug logging
client.debug(true)// Disable debug logging
client.debug(false)Release Tag: public
Get the library version from package.json.
string// Get version
const version = client.getLibraryVersion()
console.log(`Using PostHog SDK version: ${version}`)Release Tag: public
Get a persisted property value from memory storage.
key (PostHogPersistedProperty) - The property key to retrieveUnion of:
anyundefined// Get user ID
const userId = client.getPersistedProperty('userId')// Get session ID
const sessionId = client.getPersistedProperty('sessionId')Release Tag: public
Set a persisted property value in memory storage.
key (PostHogPersistedProperty) - The property key to setvalue (any | null) - The value to store (null to remove)void// Set user ID
client.setPersistedProperty('userId', 'user_123')// Set session ID
client.setPersistedProperty('sessionId', 'session_456')Release Tag: public
Shuts down the PostHog instance and ensures all events are sent. Call shutdown() once before the process exits to 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. Use flush() for per-request cleanup instead.
shutdownTimeoutMs? (number) - Maximum time to wait for shutdown in millisecondsPromise<void>// shutdown before process exit
process.on('SIGINT', async () => {
await posthog.shutdown()
process.exit(0)
})Release Tag: public
Create an alias to link two distinct IDs together.
data ({ distinctId: string; alias: string; disableGeoip?: boolean; }) - The alias data containing distinctId and aliasvoid// Link an anonymous user to an identified user
client.alias({
distinctId: 'anonymous_123',
alias: 'user_456'
})Release Tag: public
Create an alias to link two distinct IDs together immediately (synchronously).
data ({ distinctId: string; alias: string; disableGeoip?: boolean; }) - The alias data containing distinctId and aliasPromise<void>// Link an anonymous user to an identified user immediately
await client.aliasImmediate({
distinctId: 'anonymous_123',
alias: 'user_456'
})Release Tag: public
Get the custom user agent string for this client.
string// Get user agent
const userAgent = client.getCustomUserAgent()
// Returns: "posthog-node/5.7.0"Release Tag: public
Create or update a group and its properties.
{ groupType, groupKey, properties, distinctId, disableGeoip } (GroupIdentifyMessage)void// Create a company group
client.groupIdentify({
groupType: 'company',
groupKey: 'acme-corp',
properties: {
name: 'Acme Corporation',
industry: 'Technology',
employee_count: 500
},
distinctId: 'user_123'
})// Update organization properties
client.groupIdentify({
groupType: 'organization',
groupKey: 'org-456',
properties: {
plan: 'enterprise',
region: 'US-West'
}
})Release Tag: public
Identify a user and set their properties.
{ distinctId, properties, disableGeoip } (IdentifyMessage)void// Basic identify with properties
client.identify({
distinctId: 'user_123',
properties: {
name: 'John Doe',
email: 'john@example.com',
plan: 'premium'
}
})// Using $set and $set_once
client.identify({
distinctId: 'user_123',
properties: {
$set: { name: 'John Doe', email: 'john@example.com' },
$set_once: { first_login: new Date().toISOString() }
$anon_distinct_id: 'anonymous_user_456'
}
})Release Tag: public
Identify a user and set their properties immediately (synchronously).
{ distinctId, properties, disableGeoip } (IdentifyMessage)Promise<void>// Basic immediate identify
await client.identifyImmediate({
distinctId: 'user_123',
properties: {
name: 'John Doe',
email: 'john@example.com'
}
})Release Tag: public
Capture an event manually.
props (EventMessage) - The event propertiesvoid// Basic capture
client.capture({
distinctId: 'user_123',
event: 'button_clicked',
properties: { button_color: 'red' }
})Release Tag: public
Capture an event immediately (synchronously).
props (EventMessage) - The event propertiesPromise<void>// Basic immediate capture
await client.captureImmediate({
distinctId: 'user_123',
event: 'button_clicked',
properties: { button_color: 'red' }
})// With feature flags
await client.captureImmediate({
distinctId: 'user_123',
event: 'user_action',
sendFeatureFlags: true
})// With custom feature flags options
await client.captureImmediate({
distinctId: 'user_123',
event: 'user_action',
sendFeatureFlags: {
onlyEvaluateLocally: true,
personProperties: { plan: 'premium' },
groupProperties: { org: { tier: 'enterprise' } }
flagKeys: ['flag1', 'flag2']
}
})Release Tag: public
Capture an error exception as an event.
error (unknown) - The error to capturedistinctId? (string) - Optional user distinct IDadditionalProperties? (Record<string | number, any>) - Optional additional properties to includeuuid? (EventMessage['uuid']) - Optional event UUIDflags? (FeatureFlagEvaluations) - Optional FeatureFlagEvaluations snapshot to attach the same flag context as your other eventsvoid// Capture an error with user ID
try {
// Some risky operation
riskyOperation()
} catch (error) {
client.captureException(error, 'user_123')
}// Capture with additional properties
try {
apiCall()
} catch (error) {
client.captureException(error, 'user_123', {
endpoint: '/api/users',
method: 'POST',
status_code: 500
})
}Release Tag: public
Capture an error exception as an event immediately (synchronously).
error (unknown) - The error to capturedistinctId? (string) - Optional user distinct IDadditionalProperties? (Record<string | number, any>) - Optional additional properties to includeflags? (FeatureFlagEvaluations) - Optional FeatureFlagEvaluations snapshot to attach the same flag context as your other eventsPromise<void>// Capture an error immediately with user ID
try {
// Some risky operation
riskyOperation()
} catch (error) {
await client.captureExceptionImmediate(error, 'user_123')
}// Capture with additional properties
try {
apiCall()
} catch (error) {
await client.captureExceptionImmediate(error, 'user_123', {
endpoint: '/api/users',
method: 'POST',
status_code: 500
})
}Release Tag: public
Disable the PostHog client (opt-out).
Promise<void>// Disable client
await client.disable()
// Client is now disabled and will not capture eventsRelease Tag: public
Enable the PostHog client (opt-in).
Promise<void>// Enable client
await client.enable()
// Client is now enabled and will capture eventsRelease Tag: public
Evaluate all feature flags for a user in a single call and return a snapshot. Branch on .isEnabled() / .getFlag(), then pass the same snapshot to capture() via the flags option so the captured event carries the exact flag values the code branched on.
Prefer this over repeated isFeatureEnabled() / getFeatureFlag() calls and over capture({ sendFeatureFlags: true }) — it consolidates flag evaluation into a single /flags request per incoming request.
Local evaluation is transparent. When the poller can resolve a flag from cached definitions, no network call is made and the snapshot’s $feature_flag_called events are tagged locally_evaluated: true.
Trim the request. Pass flagKeys to scope the underlying /flags request to a subset of flags — useful when you only need a few flags and want to reduce the response payload.
Trim the event payload. Use flags.only([...]) or flags.onlyAccessed() to filter which flags get attached to a captured event without re-fetching.
options? (AllFlagsOptions) - Optional configuration for flag evaluation. Supports the same fields as getAllFlags(), including flagKeys to scope the /flags request.Promise<FeatureFlagEvaluations>Basic usage:
const flags = await client.evaluateFlags('user_123', {
personProperties: { plan: 'enterprise' },
})
if (flags.isEnabled('new-dashboard')) {
renderNewDashboard()
}
client.capture({ distinctId: 'user_123', event: 'page_viewed', flags })Scope the request to specific keys:
const flags = await client.evaluateFlags('user_123', {
flagKeys: ['new-dashboard', 'checkout-flow'],
personProperties: { plan: 'enterprise' },
})Attach only the flags the developer actually checked:
const flags = await client.evaluateFlags('user_123')
if (flags.isEnabled('new-dashboard')) { ... }
client.capture({ distinctId: 'user_123', event: 'page_viewed', flags: flags.onlyAccessed() })Use to avoid repeating the distinctId:
await client.withContext({ distinctId: 'user_123' }, async () => {
const flags = await client.evaluateFlags()
if (flags.isEnabled('new-dashboard')) { ... }
client.capture({ event: 'page_viewed', flags })
})Release Tag: public
Get all feature flag values for a specific user.
options? (AllFlagsOptions) - Optional configuration for flag evaluationPromise<Record<string, FeatureFlagValue>>// 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' }// With specific flag keys
const specificFlags = await client.getAllFlags('user_123', {
flagKeys: ['flag-1', 'flag-2']
})// With groups and properties
const orgFlags = await client.getAllFlags('user_123', {
groups: { organization: 'acme-corp' },
personProperties: { plan: 'enterprise' }
})Release Tag: public
Get all feature flag values and payloads for a specific user.
options? (AllFlagsOptions) - Optional configuration for flag evaluationPromise<PostHogFlagsAndPayloadsResponse>// 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)// With specific flag keys
const result = await client.getAllFlagsAndPayloads('user_123', {
flagKeys: ['flag-1', 'flag-2']
})// Only evaluate locally
const result = await client.getAllFlagsAndPayloads('user_123', {
onlyEvaluateLocally: true
})Release Tag: deprecated
Get the value of a feature flag for a specific user.
key (string) - The feature flag keydistinctId (string) - The user’s distinct IDoptions? ({ groups?: Record<string, string>; personProperties?: Record<string, string>; groupProperties?: Record<string, Record<string, string>>; onlyEvaluateLocally?: boolean; sendFeatureFlagEvents?: boolean; disableGeoip?: boolean; }) - Optional configuration for flag evaluationUnion of:
Promise<FeatureFlagValueundefined>// 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
}// With groups and properties
const flagValue = await client.getFeatureFlag('org-feature', 'user_123', {
groups: { organization: 'acme-corp' },
personProperties: { plan: 'enterprise' },
groupProperties: { organization: { tier: 'premium' } }
})// Only evaluate locally
const flagValue = await client.getFeatureFlag('local-flag', 'user_123', {
onlyEvaluateLocally: true
})Release Tag: deprecated
Get the payload for a feature flag.
key (string) - The feature flag keydistinctId (string) - The user’s distinct IDmatchValue? (FeatureFlagValue) - Optional match value to get payload foroptions? ({ groups?: Record<string, string>; personProperties?: Record<string, string>; groupProperties?: Record<string, Record<string, string>>; onlyEvaluateLocally?: boolean; sendFeatureFlagEvents?: boolean; disableGeoip?: boolean; }) - Optional configuration for flag evaluationUnion of:
Promise<JsonTypeundefined>// Get payload for a feature flag
const payload = await client.getFeatureFlagPayload('flag-key', 'user_123')
if (payload) {
console.log('Flag payload:', payload)
}// Get payload with specific match value
const payload = await client.getFeatureFlagPayload('flag-key', 'user_123', 'variant-a')// With groups and properties
const payload = await client.getFeatureFlagPayload('org-flag', 'user_123', undefined, {
groups: { organization: 'acme-corp' },
personProperties: { plan: 'enterprise' }
})Release Tag: public
Get the result of evaluating a feature flag, including its value and payload. This is more efficient than calling getFeatureFlag and getFeatureFlagPayload separately when you need both.
key (string) - The feature flag keyoptions? (FlagEvaluationOptions) - Optional configuration for flag evaluationUnion of:
Promise<FeatureFlagResultundefined>// Get flag result
const result = await client.getFeatureFlagResult('my-flag', 'user_123')
if (result) {
console.log('Flag enabled:', result.enabled)
console.log('Variant:', result.variant)
console.log('Payload:', result.payload)
}// With groups and properties
const result = await client.getFeatureFlagResult('org-feature', 'user_123', {
groups: { organization: 'acme-corp' },
personProperties: { plan: 'enterprise' }
})Release Tag: public
Get the remote config payload for a feature flag.
flagKey (string) - The feature flag keyUnion of:
Promise<JsonTypeundefined>// Get remote config payload
const payload = await client.getRemoteConfigPayload('flag-key')
if (payload) {
console.log('Remote config payload:', payload)
}Release Tag: deprecated
Check if a feature flag is enabled for a specific user.
key (string) - The feature flag keydistinctId (string) - The user’s distinct IDoptions? ({ groups?: Record<string, string>; personProperties?: Record<string, string>; groupProperties?: Record<string, Record<string, string>>; onlyEvaluateLocally?: boolean; sendFeatureFlagEvents?: boolean; disableGeoip?: boolean; }) - Optional configuration for flag evaluationUnion of:
Promise<booleanundefined>// 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')
}// With groups and properties
const isEnabled = await client.isFeatureEnabled('org-feature', 'user_123', {
groups: { organization: 'acme-corp' },
personProperties: { plan: 'enterprise' }
})Release Tag: public
Check if local evaluation of feature flags is ready.
boolean// 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')
}Release Tag: public
Override feature flags locally. Useful for testing and local development. Overridden flags take precedence over both local evaluation and remote evaluation.
overrides (OverrideFeatureFlagsOptions) - Flag overrides configurationvoid// Clear all overrides
client.overrideFeatureFlags(false)
// Enable a list of flags (sets them to true)
client.overrideFeatureFlags(['flag-a', 'flag-b'])
// Set specific flag values/variants
client.overrideFeatureFlags({ 'my-flag': 'variant-a', 'other-flag': true })
// Set both flags and payloads
client.overrideFeatureFlags({
flags: { 'my-flag': 'variant-a' },
payloads: { 'my-flag': { discount: 20 } }
})Release Tag: public
Reload feature flag definitions from the server for local evaluation.
Promise<void>// Force reload of feature flags
await client.reloadFeatureFlags()
console.log('Feature flags reloaded')// Reload before checking a specific flag
await client.reloadFeatureFlags()
const flag = await client.getFeatureFlag('flag-key', 'user_123')Release Tag: public
Wait for local evaluation of feature flags to be ready.
timeoutMs? (number) - Timeout in milliseconds (default: 30000)Promise<boolean>// Wait for local evaluation
const isReady = await client.waitForLocalEvaluationReady()
if (isReady) {
console.log('Local evaluation is ready')
} else {
console.log('Local evaluation timed out')
}// Wait with custom timeout
const isReady = await client.waitForLocalEvaluationReady(10000) // 10 secondsRelease Tag: public
Get the current context data.
Union of:
ContextDataundefined// Get current context within a withContext block
posthog.withContext({ distinctId: 'user_123' }, () => {
const context = posthog.getContext()
console.log(context?.distinctId) // 'user_123'
})Release Tag: public
Run a function with specific context that will be applied to all events captured within that context. It propagates the context to all subsequent calls down the call stack. Context properties like tags and sessionId will be automatically attached to all events. By default, nested contexts inherit from parent contexts. Use { fresh: true } to start with a clean context.
data (Partial<ContextData>) - Context data to apply (sessionId, distinctId, properties, enableExceptionAutocapture)fn (() => T) - Function to run with the contextoptions? (ContextOptions) - Context options (fresh: true to start with clean context instead of inheriting)Tposthog.withContext({ distinctId: 'user_123' }, () => {
posthog.capture({ event: 'button clicked' })
})This file