Node.js library

Last updated:

This is the official PostHog library for Node.js to capture and send events to any PostHog instance.

View on GitHub

If you're working with Node.js, the official posthog-node library is the simple way to integrate your software with PostHog. This library uses an internal queue to make calls fast and non-blocking. It also batches requests and flushes asynchronously, making it perfect to use in any part of your web app or other server-side application that needs performance. And in addition to event capture, feature flags are supported as well.

Installation

Run either npm or yarn in terminal to add it to your project:

npm install posthog-node --save
# or
yarn add posthog-node

In your app, set your API key before making any calls.

import PostHog from 'posthog-node'
const client = new PostHog(
'<ph_project_api_key>',
{ host: '<ph_instance_address>' } // You can omit this line if using PostHog Cloud
)
// On program exit, call shutdown to stop pending pollers and flush any remaining events
client.shutdown()

You can find your key in the 'Project Settings' page in PostHog.

Note: As a rule of thumb, we do not recommend hardcoding API keys. Setting it as an environment variable would be best.

Options

VariableDescriptionDefault value
hostYour PostHog hosthttps://app.posthog.com/
flushAtAfter how many capture calls we should flush the queue (in one batch)20
flushIntervalAfter how many ms we should flush the queue10000
personalApiKeyAn optional personal API key for using feature flagsnull
featureFlagsPollingIntervalInterval in milliseconds specifying how often feature flags should be fetched from the PostHog API300000

Note: When using PostHog in an AWS Lambda function or a similar serverless function environment, make sure you set flushAt and flushInterval to 0.

Making calls

Capture

Capture allows you to capture anything a user does within your system, which you can later use in PostHog to find patterns in usage, work out which features to improve or where people are giving up.

A capture call requires:

  • distinct id which uniquely identifies your user
  • event name to identify the event
  • We recommend naming events with "[noun][verb]", such as movie played or movie updated, in order to easily identify what your events mean later on (we know this from experience).

Optionally you can submit:

  • properties, which is an object with any information you'd like to add

For example:

client.capture({
distinctId: 'distinct id',
event: 'movie played',
properties: {
movieId: '123',
category: 'romcom'
}
})

Setting user properties via an event

To set properties on your users via an event, you can leverage the event properties $set and $set_once.

$set

Example

client.capture({
distinctId: 'distinct id',
event: 'movie played',
properties: {
$set: { userProperty: 'value' }
}
})

Usage

When capturing an event, you can pass a property called $set as an event property, and specify its value to be an object with properties to be set on the user that will be associated with the user who triggered the event.

$set_once

Example

client.capture({
distinctId: 'distinct id',
event: 'movie played',
properties: {
$set_once: { userProperty: 'value' }
}
})

Usage

$set_once works just like $set, except that it will only set the property if the user doesn't already have that property set.

Identify

We highly recommend reading our section on Identifying users to better understand how to correctly use this method.

Identify lets you add metadata to your users so you can easily identify who they are in PostHog, as well as do things like segment users by these properties.

An identify call requires:

  • distinctId – a distinct ID belonging to the user
  • properties – a user properties object

For example:

client.identify({
distinctId: "user:123",
properties: {
email: 'john@doe.com',
proUser: false
}
})

The most obvious place to make this call is whenever a user signs up, or when they update their information.

Alias

To connect whatever a user does before they sign up or log in with what they do after you need to make an alias call. This will allow you to answer questions like "Which marketing channels leads to users churning after a month?" or "What do users do on our website before signing up?"

In a purely back-end implementation, this means whenever an anonymous user does something, you'll want to send a session ID with the capture call. Then, when that users signs up, you want to do an alias call with the session ID and the newly created user ID.

The same concept applies for when a user logs in.

If you're using PostHog in the front-end and back-end, doing the identify call in the frontend will be enough.

An alias call requires:

  • distinctId – the current distinct ID of the user
  • alias – the other distinct ID of the user, which will be aliased to the current one

For example:

client.alias({
distinctId: "user:123",
alias: "user:12345",
})

Sending page views

If you're aiming for a full back-end implementation of PostHog, you can send pageviews from your backend, like so:

client.capture({
distinctId: 'distinct id',
event: '$pageview',
properties: {
$current_url: 'https://example.com'
}
})

Feature flags

Note that to use feature flags you must specify personalApiKey in options passed to the PostHog constructor.

Checking if a feature is enabled

To check if a feature flag is on for a given user, you can call isFeatureEnabled, passing the flag's key and the user's distinct ID. You can optionally pass a third argument to override the default result to be returned if the flag is not found. This is set to false by default.

// isFeatureEnabled(key: string, distinctId: string, defaultResult?: boolean): Promise<boolean>
const isMyFlagEnabledForUser = await client.isFeatureEnabled('flag-key', 'user distinct id')
if (isMyFlagEnabledForUser) {
// Do something differently for this user
}

If your feature flag relies entirely on rollout percentage (i.e. it has no filters), isFeatureEnabled will provide a fast response, allowing it to be used in the logic for API endpoints, for example. Flags that depend on filters require a call to the PostHog API so will take longer.

Reloading feature flags

When initializing PostHog, you can configure the interval at which feature flags are polled (fetched from the server). However, if you need to force a reload, you can use reloadFeatureFlags:

await client.reloadFeatureFlags()
// Do something with feature flags here

Shutdown

You should call shutdown on your program's exit to exit cleanly:

// Stop pending pollers and flush any remaining events
client.shutdown()