From d2c6729750f5706c85c8aefb24aaa32888253d66 Mon Sep 17 00:00:00 2001 From: "wizard-ci-bot[bot]" <254716194+wizard-ci-bot[bot]@users.noreply.github.com> Date: Wed, 9 Sep 2026 22:21:09 +0000 Subject: [PATCH] wizard-ci: javascript-node/native-http-contacts --- .../.posthog-wizard | 0 .../references/identify-users.md | 307 ++++ .../references/node.md | 897 ++++++++++ .../references/posthog-node.md | 1590 +++++++++++++++++ .../native-http-contacts/.env.example | 2 + .../native-http-contacts/index.js | 45 +- .../native-http-contacts/package-lock.json | 63 + .../native-http-contacts/package.json | 5 +- .../native-http-contacts/posthog.js | 19 + 9 files changed, 2926 insertions(+), 2 deletions(-) create mode 100644 apps/basic-integration/javascript-node/native-http-contacts/.claude/skills/integration-javascript_node/.posthog-wizard create mode 100644 apps/basic-integration/javascript-node/native-http-contacts/.claude/skills/integration-javascript_node/references/identify-users.md create mode 100644 apps/basic-integration/javascript-node/native-http-contacts/.claude/skills/integration-javascript_node/references/node.md create mode 100644 apps/basic-integration/javascript-node/native-http-contacts/.claude/skills/integration-javascript_node/references/posthog-node.md create mode 100644 apps/basic-integration/javascript-node/native-http-contacts/.env.example create mode 100644 apps/basic-integration/javascript-node/native-http-contacts/package-lock.json create mode 100644 apps/basic-integration/javascript-node/native-http-contacts/posthog.js diff --git a/apps/basic-integration/javascript-node/native-http-contacts/.claude/skills/integration-javascript_node/.posthog-wizard b/apps/basic-integration/javascript-node/native-http-contacts/.claude/skills/integration-javascript_node/.posthog-wizard new file mode 100644 index 000000000..e69de29bb diff --git a/apps/basic-integration/javascript-node/native-http-contacts/.claude/skills/integration-javascript_node/references/identify-users.md b/apps/basic-integration/javascript-node/native-http-contacts/.claude/skills/integration-javascript_node/references/identify-users.md new file mode 100644 index 000000000..8647dcb37 --- /dev/null +++ b/apps/basic-integration/javascript-node/native-http-contacts/.claude/skills/integration-javascript_node/references/identify-users.md @@ -0,0 +1,307 @@ +> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt + +# Identify users - Docs + +Copy page + +# Identify users - Docs + +Linking events to specific users enables you to build a full picture of how they're using your product across different sessions, devices, and platforms. + +This is straightforward to do when [capturing backend events](/docs/product-analytics/capture-events?tab=Node.js.md), as you associate events to a specific user using a `distinct_id`, which is a required argument. + +However, in the frontend of a [web](/docs/libraries/js/usage.md#capturing-events) or [mobile app](/docs/libraries/ios.md#capturing-events), a `distinct_id` is not a required argument — PostHog's SDKs will generate an anonymous `distinct_id` for you automatically and you can capture events anonymously, provided you use the appropriate [configuration](/docs/libraries/js/usage.md#capturing-anonymous-events). + +To link events to specific users, call `identify`: + +PostHog AI + +### Web + +```javascript +posthog.identify( + 'distinct_id', // Replace 'distinct_id' with your user's unique identifier + { email: 'max@hedgehogmail.com', name: 'Max Hedgehog' } // optional: set additional person properties +); +``` + +### Android + +```kotlin +PostHog.identify( + distinctId = distinctID, // Replace 'distinctID' with your user's unique identifier + // optional: set additional person properties + userProperties = mapOf( + "name" to "Max Hedgehog", + "email" to "max@hedgehogmail.com" + ) +) +``` + +### iOS + +```swift +PostHogSDK.shared.identify("distinct_id", // Replace "distinct_id" with your user's unique identifier + userProperties: ["name": "Max Hedgehog", "email": "max@hedgehogmail.com"]) // optional: set additional person properties +``` + +### React Native + +```jsx +posthog.identify('distinct_id', { // Replace "distinct_id" with your user's unique identifier + email: 'max@hedgehogmail.com', // optional: set additional person properties + name: 'Max Hedgehog' +}) +``` + +### Dart + +```dart +await Posthog().identify( + userId: 'distinct_id', // Replace "distinct_id" with your user's unique identifier + userProperties: { + 'email': 'max@hedgehogmail.com', // optional: set additional person properties + 'name': 'Max Hedgehog', + }, +); +``` + +Events captured after calling `identify` are identified events and this creates a person profile if one doesn't exist already. + +Due to the cost of processing them, anonymous events can be up to 4x cheaper than identified events, so it's recommended you only capture identified events when needed. + +## How identify works + +When a user starts browsing your website or app, PostHog automatically assigns them an **anonymous ID**, which is stored locally. + +Provided you've [configured persistence](/docs/libraries/js/persistence.md) to use cookies or `localStorage`, this enables us to track anonymous users – even across different sessions. + +By calling `identify` with a `distinct_id` of your choice (usually the user's ID in your database, or their email), you link the anonymous ID and distinct ID together. + +Thus, all past and future events made with that anonymous ID are now associated with the distinct ID. + +This enables you to do things like associate events with a user from before they log in for the first time, or associate their events across different devices or platforms. + +Using identify in the backend + +Although you can call `identify` using our backend SDKs, it is used most in frontends. This is because there is no concept of anonymous sessions in the backend SDKs, so calling `identify` only updates person profiles. + +## Best practices when using `identify` + +### 1\. Call `identify` as soon as you're able to + +In your frontend, you should call `identify` as soon as you're able to. + +Typically, this is every time your **app loads** for the first time, and directly after your **users log in**. + +This ensures that events sent during your users' sessions are correctly associated with them. + +You only need to call `identify` once per session, and you should avoid calling it multiple times unnecessarily. + +If you call `identify` multiple times with the same data without reloading the page in between, PostHog will ignore the subsequent calls. + +#### Identify users when the web SDK loads + +If your app already knows the signed-in user when you initialize the JavaScript web SDK, the [`loaded` callback](/docs/libraries/js/config.md) is a convenient place to call `identify`. This identifies the user as soon as the SDK has loaded: + +Web + +PostHog AI + +```javascript +posthog.init('', { + api_host: 'https://us.i.posthog.com', + defaults: '2026-05-30', + loaded: (posthog) => { + if (currentUser?.id) { + posthog.identify(currentUser.id, { + email: currentUser.email, + name: currentUser.name, + }) + } + }, +}) +``` + +In this example, `currentUser` represents user data already available from your authentication system. If your app loads the user asynchronously, call `posthog.identify()` as soon as that data becomes available instead. + +### 2\. Use unique strings for distinct IDs + +If two users have the same distinct ID, their data is merged and they are considered one user in PostHog. Two common ways this can happen are: + +- Your logic for generating IDs does not generate sufficiently strong IDs and you can end up with a clash where 2 users have the same ID. +- There's a bug, typo, or mistake in your code leading to most or all users being identified with generic IDs like `null`, `true`, or `distinctId`. + +PostHog also has built-in protections to stop the most common distinct ID mistakes. + +### 3\. Reset after logout + +If a user logs out on your frontend, you should call `reset()` to unlink any future events made on that device with that user. + +This is important if your users are sharing a computer, as otherwise all of those users are grouped together into a single user due to shared cookies between sessions. + +**We strongly recommend you call `reset` on logout even if you don't expect users to share a computer.** + +You can do that like so: + +PostHog AI + +### Web + +```javascript +posthog.reset() +``` + +### iOS + +```swift +PostHogSDK.shared.reset() +``` + +### Android + +```kotlin +PostHog.reset() +``` + +### React Native + +```jsx +posthog.reset() +``` + +### Dart + +```dart +await Posthog().reset(); +``` + +If you *also* want to reset the `device_id` so that the device will be considered a new device in future events, you can pass `true` as an argument: + +Web + +PostHog AI + +```javascript +posthog.reset(true) +``` + +### 4\. Person profiles and properties + +You'll notice that one of the parameters in the `identify` method is a `properties` object. + +This enables you to set [person properties](/docs/product-analytics/person-properties.md). + +Whenever possible, we recommend passing in all person properties you have available each time you call identify, as this ensures their person profile on PostHog is up to date. + +Person properties can also be set being adding a `$set` property to a event `capture` call. + +**\`$set\` and \`$set\_once\` aren't stored on events** + +These properties only tell PostHog how to update person data during ingestion — they aren't kept on the stored event, so you can't filter, break down, or query events by them. To query the values you set, use [person properties](/docs/product-analytics/person-properties.md) instead. + +See our [person properties docs](/docs/product-analytics/person-properties.md) for more details on how to work with them and best practices. + +### 5\. Use deep links between platforms + +We recommend you call `identify` [as soon as you're able](#1-call-identify-as-soon-as-youre-able), typically when a user signs up or logs in. + +This doesn't work if one or both platforms are unauthenticated. Some examples of such cases are: + +- Onboarding and signup flows before authentication. +- Unauthenticated web pages redirecting to authenticated mobile apps. +- Authenticated web apps prompting an app download. + +In these cases, you can use a [deep link](https://developer.android.com/training/app-links/deep-linking) on Android and [universal links](https://developer.apple.com/documentation/xcode/supporting-universal-links-in-your-app) on iOS to identify users. + +1. Use `posthog.get_distinct_id()` to get the current distinct ID. Even if you cannot call identify because the user is unauthenticated, this will return an anonymous distinct ID generated by PostHog. +2. Add the distinct ID to the deep link as query parameters, along with other properties like UTM parameters. +3. When the user is redirected to the app, parse the deep link and handle the following cases: + +- The mobile app is already authenticated. In this case, call [`posthog.alias()`](/docs/libraries/js/usage.md#alias) with the distinct ID from the web. This associates the two distinct IDs as a single person. +- The mobile app is unauthenticated. In this case, call [`posthog.identify()`](/docs/libraries/js/usage.md#identifying-users) with the distinct ID from the web so pre-login mobile events stay connected to the web session. When the user later logs in on mobile, call `identify()` again with your canonical user ID. + +As long as you associate the distinct IDs with `posthog.identify()` or `posthog.alias()`, you can track events generated across platforms. + +Here's an example implementation for handling deep links from web to mobile: + +PostHog AI + +### iOS + +```swift +import PostHog +class DeepLinkIdentityManager { + static let shared = DeepLinkIdentityManager() + // MARK: - Deep Link Received + func handleDeepLink(_ url: URL, isAuthenticatedOnMobile: Bool) { + guard let webDistinctId = URLComponents(url: url, resolvingAgainstBaseURL: true)? + .queryItems?.first(where: { $0.name == "ph_distinct_id" })?.value else { + return + } + if isAuthenticatedOnMobile { + // The mobile app already knows the current user. + // Alias the incoming web distinct ID to that user. + PostHogSDK.shared.alias(webDistinctId) + } else { + // Reuse the web distinct ID until login on mobile. + PostHogSDK.shared.identify(webDistinctId) + } + } + // MARK: - Login/Signup + func handleLogin(canonicalUserId: String) { + // Switch from the web distinct ID (or a mobile anon ID) + // to your canonical user ID. + PostHogSDK.shared.identify(canonicalUserId) + // Set user properties, track signup event, etc. + } + func handleLogout() { + PostHogSDK.shared.reset() + } +} +``` + +### Android + +```kotlin +import android.net.Uri +import com.posthog.PostHog +object DeepLinkIdentityManager { + // Deep Link Received + fun handleDeepLink(uri: Uri, isAuthenticatedOnMobile: Boolean) { + val webDistinctId = uri.getQueryParameter("ph_distinct_id") ?: return + if (isAuthenticatedOnMobile) { + // The mobile app already knows the current user. + // Alias the incoming web distinct ID to that user. + PostHog.alias(webDistinctId) + } else { + // Reuse the web distinct ID until login on mobile. + PostHog.identify(webDistinctId) + } + } + // Login/Signup + fun handleLogin(canonicalUserId: String) { + // Switch from the web distinct ID (or a mobile anon ID) + // to your canonical user ID. + PostHog.identify(canonicalUserId) + // Set user properties, track signup event, etc. + } + fun handleLogout() { + PostHog.reset() + } +} +``` + +## Further reading + +- [Identifying users docs](/docs/product-analytics/identify.md) +- [How person processing works](/docs/how-posthog-works/ingestion-pipeline.md#2-person-processing) +- [An introductory guide to identifying users in PostHog](/tutorials/identifying-users-guide.md) + +### Still have questions? + +Ask PostHog AI + +### Was this page useful? + +HelpfulCould be better \ No newline at end of file diff --git a/apps/basic-integration/javascript-node/native-http-contacts/.claude/skills/integration-javascript_node/references/node.md b/apps/basic-integration/javascript-node/native-http-contacts/.claude/skills/integration-javascript_node/references/node.md new file mode 100644 index 000000000..1c9341bb5 --- /dev/null +++ b/apps/basic-integration/javascript-node/native-http-contacts/.claude/skills/integration-javascript_node/references/node.md @@ -0,0 +1,897 @@ +> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt + +# Node.js - Docs + +Copy page + +# Node.js - Docs + +If you're working with Node.js (versions 20+), the official `posthog-node` library is the simplest 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](/docs/feature-flags.md) are supported as well. + +## Installation + +Run either `npm` or `yarn` in terminal to add it to your project: + +PostHog AI + +### npm + +```bash +npm install posthog-node --save +``` + +### Yarn + +```bash +yarn add posthog-node +``` + +### pnpm + +```bash +pnpm add posthog-node +``` + +### Bun + +```bash +bun add posthog-node +``` + +In your app, set your project token **before** making any calls. + +Node.js + +PostHog AI + +```javascript +import { PostHog } from 'posthog-node' +const client = new PostHog( + '', + { host: 'https://us.i.posthog.com' } +) +await client.shutdown() +``` + +You can find your project token and instance address in the [project settings](https://app.posthog.com/project/settings) page in PostHog. + +> **Note:** As a rule of thumb, we do not recommend hardcoding API keys or tokens. Setting it as an environment variable is preferred. + +## Identifying users + +> **Identifying users is required.** Backend events need a `distinct_id` that matches the ID your frontend uses when calling `posthog.identify()`. Without this, backend events are orphaned — they can't be linked to frontend event captures, [session replays](/docs/session-replay.md), [LLM traces](/docs/ai-engineering.md), or [error tracking](/docs/error-tracking.md). +> +> See our guide on [identifying users](/docs/getting-started/identify-users.md) for how to set this up. + +### Options + +| Variable | Description | Default value | +| --- | --- | --- | +| host | Your PostHog host | https://us.i.posthog.com/ | +| flushAt | After how many capture calls we should flush the queue (in one batch) | 20 | +| flushInterval | After how many ms we should flush the queue | 10000 | +| personalApiKey | An optional [personal API key](/docs/api/overview.md#personal-api-keys-recommended) for evaluating feature flags locally. Note: Providing this will trigger periodic calls to the feature flags service, even if you're not using feature flags. | null | +| featureFlagsPollingInterval | Interval in milliseconds specifying how often feature flags should be fetched from the PostHog API | 300000 | +| requestTimeout | Timeout in milliseconds for any calls | 10000 | +| maxCacheSize | Maximum size of cache that deduplicates $feature_flag_called calls per user. | 50000 | +| disableGeoip | When true, disables automatic GeoIP resolution for events and feature flags. | true | +| isServer | Controls the $is_server event property. Keep the default for server-side events. Set to false when using posthog-node from a client-like runtime, CLI, or desktop app so device OS attribution is handled normally. | true | +| evaluationContexts | Evaluation context tags that constrain which feature flags are evaluated. When set, only flags with matching evaluation context tags (or no evaluation context tags) will be returned. This helps reduce unnecessary flag evaluations and improves performance. See [evaluation contexts documentation](/docs/feature-flags/evaluation-contexts.md) for more details. Available in version 5.23.0+. The legacy parameter evaluationEnvironments (version 5.10.0+) is also supported for backward compatibility. | undefined | + +> **Note:** When using PostHog in an AWS Lambda function or a similar serverless function environment, make sure you set `flushAt` to `1` and `flushInterval` to `0`. Also, remember to always call `await posthog.shutdown()` at the end to flush and send all pending events. + +## Capturing events + +You can send custom events using `capture`: + +Node.js + +PostHog AI + +```javascript +client.capture({ + distinctId: 'distinct_id_of_the_user', + event: 'user signed up', +}) +``` + +> **Tip:** We recommend using a `[object] [verb]` format for your event names, where `[object]` is the entity that the behavior relates to, and `[verb]` is the behavior itself. For example, `project created`, `user signed up`, or `invite sent`. + +### Setting event properties + +Optionally, you can include additional information with the event by including a [properties](/docs/data/events.md#event-properties) object: + +Node.js + +PostHog AI + +```javascript +client.capture({ + distinctId: 'distinct_id_of_the_user', + event: 'user signed up', + properties: { + login_type: 'email', + is_free_trial: true, + }, +}) +``` + +### Capturing pageviews + +If you're aiming for a backend-only implementation of PostHog and won't be capturing events from your frontend, you can send `$pageview` events from your backend like so: + +Node.js + +PostHog AI + +```javascript +client.capture({ + distinctId: 'distinct_id_of_the_user', + event: '$pageview', + properties: { + $current_url: 'https://example.com', + }, +}) +``` + +## Person profiles and properties + +The Node SDK captures identified events by default. These create [person profiles](/docs/data/persons.md). To set [person properties](/docs/product-analytics/person-properties.md) in these profiles, include them when capturing an event using `$set` and `$set_once`: + +Node.js + +PostHog AI + +```javascript +client.capture({ + distinctId: 'distinct_id_of_the_user', + event: 'movie_played', + properties: { + $set: { name: 'Max Hedgehog' }, + $set_once: { initial_url: '/blog' }, + }, +}) +``` + +For more details on the difference between `$set` and `$set_once`, see our [person properties docs](/docs/product-analytics/person-properties.md#what-is-the-difference-between-set-and-set_once). + +You can also use helper methods to set or remove person properties without hand-building `$set`, `$set_once`, or `$unset` payloads. See [person properties](/docs/product-analytics/person-properties.md) for examples. + +To capture [anonymous events](/docs/data/anonymous-vs-identified-events.md) without person profiles, set the event's `$process_person_profile` property to `false`: + +Node.js + +PostHog AI + +```javascript +client.capture({ + distinctId: 'distinct_id_of_the_user', + event: 'movie_played', + properties: { + $process_person_profile: false, + }, +}) +``` + +## Alias + +Sometimes, you want to assign multiple distinct IDs to a single user. This is helpful when your primary distinct ID is inaccessible. For example, if a distinct ID used on the frontend is not available in your backend. + +In this case, you can use `alias` to assign another distinct ID to the same user. + +Node.js + +PostHog AI + +```javascript +client.alias({ + distinctId: 'distinct_id', + alias: 'alias_id', +}) +``` + +We strongly recommend reading our docs on [alias](/docs/product-analytics/identify.md#alias-assigning-multiple-distinct-ids-to-the-same-user) to best understand how to correctly use this method. + +## Super properties + +> Requires `posthog-node` version >= 5.25.0. + +Super properties are properties that are automatically included with every event captured by the client. Use `register` to set them: + +Node.js + +PostHog AI + +```javascript +client.register({ + app_version: '1.2.0', + environment: 'production', +}) +// Both events include app_version and environment +client.capture({ + distinctId: 'distinct_id', + event: 'page_viewed', +}) +client.capture({ + distinctId: 'distinct_id', + event: 'button_clicked', +}) +``` + +If an event sets a property with the same key as a super property, the event's property takes precedence: + +Node.js + +PostHog AI + +```javascript +client.register({ environment: 'production' }) +// This event is captured with environment='staging' +client.capture({ + distinctId: 'distinct_id', + event: 'page_viewed', + properties: { environment: 'staging' }, +}) +``` + +To remove a super property, use `unregister`: + +Node.js + +PostHog AI + +```javascript +client.unregister('environment') +``` + +Super properties are **global** — they apply to every event for the lifetime of the client instance. For properties that should only apply to a specific scope (e.g. a single request or transaction), use [contexts](#contexts) instead. + +## Contexts + +> Requires `posthog-node` version >= 5.17.0. + +The Node SDK uses nested contexts for managing state that's shared across events. Contexts are useful for adding properties to multiple events (including exceptions) during a single user's interaction with your product. + +You can enter a context using `withContext`: + +Node.js + +PostHog AI + +```javascript +posthog.withContext( + { + distinctId: 'user-123', + properties: { transactionId: 'abc123' } + }, + () => { + // This event is captured with the distinct ID and properties set above + posthog.capture({ event: 'order_processed' }) + } +) +``` + +Contexts are persisted across function calls. If you enter one and then call a function and capture an event in the called function, it uses the context properties set in the parent context: + +Node.js + +PostHog AI + +```javascript +function someFunction() { + // When called from `outerFunction`, this event is captured + // with transactionId='abc123' + posthog.capture({ event: 'order_processed' }) +} +function outerFunction() { + posthog.withContext( + { properties: { transactionId: 'abc123' } }, + () => { + someFunction() + } + ) +} +``` + +By default, each context inherits from parent contexts. To disable nesting (where child contexts is fresh and has no properties), pass `{ fresh: true }`: + +Node.js + +PostHog AI + +```javascript +posthog.withContext( + { + properties: { + someKey: 'value-1', + someOtherKey: 'another-value' + } + }, + () => { + posthog.withContext( + { properties: { someKey: 'value-2' } }, + () => { + // Captured with someKey='value-2', someOtherKey='another-value' + posthog.capture({ event: 'order_processed' }) + }, + ) + // Captured with someKey='value-1', someOtherKey='another-value' + posthog.capture({ event: 'order_completed' }) + } +) +``` + +> **Note:** Properties passed directly to `capture` calls override context state in the final event. + +### Identification context + +Contexts can be associated with a distinct ID: + +Node.js + +PostHog AI + +```javascript +posthog.withContext( + { distinctId: 'user-123' }, + () => { + // Associated with "user-123" + posthog.capture({ event: 'order_processed' }) + // Overrides to "another-user" + posthog.capture({ + distinctId: 'another-user', + event: 'order_processed' + }) + } +) +``` + +### Session context + +Node.js + +PostHog AI + +```javascript +posthog.withContext( + { sessionId: 'some-session' }, + () => { + // Associated with session "some-session" + posthog.capture({ event: 'image_uploaded' }) + // Overrides to "next-session" + posthog.capture({ + event: 'image_uploaded', + properties: { $sessionId: 'next-session' } + }) + } +) +``` + +### Custom context parameters + +Node.js + +PostHog AI + +```javascript +posthog.withContext( + { flightNumber: 'TAC313' }, + () => { + // Associated with flightNumber TAC313 + posthog.capture({ event: 'flight_cancelled' }) + // Overrides to PL7714 + posthog.capture({ + event: 'flight_cancelled', + properties: { flightNumber: 'PL7714' } + }) + } +) +``` + +## Add request context to Express + +> Requires `posthog-node` version >= 5.31.0. + +If you use Express, add request-scoped PostHog context with the built-in middleware helpers. Register `setupExpressRequestContext` before your routes so events captured during a request automatically use the incoming session and distinct ID headers. Register `setupExpressErrorHandler` after your routes if you want to send Express errors to PostHog Error Tracking. + +server.ts + +PostHog AI + +```typescript +import express from 'express' +import { PostHog, setupExpressRequestContext, setupExpressErrorHandler } from 'posthog-node' +const app = express() +const posthog = new PostHog('', { + host: 'https://us.i.posthog.com', +}) +// Register before routes. +setupExpressRequestContext(posthog, app) +app.post('/checkout', (req, res) => { + posthog.capture({ event: 'checkout_started' }) + res.json({ status: 'ok' }) +}) +// Optional: register after routes to capture Express errors. +setupExpressErrorHandler(posthog, app) +``` + +The request context middleware reads the following incoming headers: + +| Header | Context property | Description | +| --- | --- | --- | +| x-posthog-session-id | sessionId | Links server events to a client session | +| x-posthog-distinct-id | distinctId | Sets the event distinct ID | + +It also automatically adds request metadata as event properties: + +- `$current_url` – the request URL +- `$request_method` – the HTTP method (GET, POST, etc.) +- `$request_path` – the request path +- `$user_agent` – the user agent string +- `$ip` – the client IP (parsed from `x-forwarded-for` if behind a proxy) + +Properties and `distinctId` passed directly to `capture` take precedence over request context. Tracing headers are client-controlled analytics context, not authentication or authorization. Pass an authenticated `distinctId` explicitly for security-sensitive server-side decisions. + +### Send headers from the client + +If you're using [PostHog JS](/docs/libraries/js.md) on the frontend, configure [`tracing_headers`](/docs/libraries/js/config.md#tracing-headers) for your Express backend hostname so browser requests include `X-POSTHOG-SESSION-ID` and `X-POSTHOG-DISTINCT-ID`, which the Express middleware reads automatically. + +## Feature flags + +PostHog's [feature flags](/docs/feature-flags.md) enable you to safely deploy and roll back new features as well as target specific users and groups with them. + +There are two steps to implement feature flags in Node: + +### Step 1: Evaluate flags once + +Call `client.evaluateFlags()` once for the user, then read values from the returned snapshot. + +#### Boolean feature flags + +Node.js + +PostHog AI + +```javascript +const flags = await client.evaluateFlags('distinct_id_of_your_user') +if (flags.isEnabled('flag-key')) { + // Do something differently for this user + // Optional: fetch the payload + const matchedFlagPayload = flags.getFlagPayload('flag-key') +} +``` + +#### Multivariate feature flags + +Node.js + +PostHog AI + +```javascript +const flags = await client.evaluateFlags('distinct_id_of_your_user') +const enabledVariant = flags.getFlag('flag-key') +if (enabledVariant === 'variant-key') { // replace 'variant-key' with the key of your variant + // Do something differently for this user + // Optional: fetch the payload + const matchedFlagPayload = flags.getFlagPayload('flag-key') +} +``` + +`flags.getFlag()` returns the variant string for multivariate flags, `true` for enabled boolean flags, `false` for disabled flags, and `undefined` when the flag wasn't returned by the evaluation. + +> **Note:** `client.isFeatureEnabled()`, `client.getFeatureFlag()`, `client.getFeatureFlagPayload()`, and `capture({ sendFeatureFlags: true })` still work during the migration period, but they're deprecated. Prefer `evaluateFlags()` for new code. + +### Step 2: Include feature flag information when capturing events + +If you want use your feature flag to breakdown or filter events in your [insights](/docs/product-analytics/insights.md), you'll need to include feature flag information in those events. This ensures that the feature flag value is attributed correctly to the event. + +> **Note:** This step is only required for events captured using our server-side SDKs or [API](/docs/api.md). + +There are two methods you can use to include feature flag information in your events: + +#### Method 1: Pass the evaluated flags snapshot to `capture()` + +Pass the same `flags` object that you used for branching. This attaches the exact flag values from that evaluation and doesn't make another `/flags` request. + +Node.js + +PostHog AI + +```javascript +const flags = await client.evaluateFlags('distinct_id_of_your_user') +if (flags.isEnabled('flag-key')) { + // Do something differently for this user +} +client.capture({ + distinctId: 'distinct_id_of_your_user', + event: 'event_name', + flags, +}) +``` + +By default, this attaches every flag in the snapshot using `$feature/` properties and `$active_feature_flags`. + +To reduce event property bloat, pass a filtered snapshot: + +Node.js + +PostHog AI + +```javascript +// Attach only flags accessed with isEnabled() or getFlag() before this call +client.capture({ + distinctId: 'distinct_id_of_your_user', + event: 'event_name', + flags: flags.onlyAccessed(), +}) +// Attach only specific flags +client.capture({ + distinctId: 'distinct_id_of_your_user', + event: 'event_name', + flags: flags.only(['checkout-flow', 'new-dashboard']), +}) +``` + +`onlyAccessed()` is order-dependent. If you call it before accessing any flags with `isEnabled()` or `getFlag()`, no feature flag properties are attached. + +#### Method 2: Include the `$feature/feature_flag_name` property manually + +In the event properties, include `$feature/feature_flag_name: variant_key`: + +Node.js + +PostHog AI + +```javascript +client.capture({ + distinctId: 'distinct_id_of_your_user', + event: 'event_name', + properties: { + // Replace feature-flag-key with your flag key and 'variant-key' with the key of your variant + '$feature/feature-flag-key': 'variant-key', + }, +}) +``` + +### Evaluating only specific flags + +By default, `evaluateFlags()` evaluates every flag for the user. If you only need a few flags, pass `flagKeys` to request only those flags: + +Node.js + +PostHog AI + +```javascript +const flags = await client.evaluateFlags('distinct_id_of_your_user', { + flagKeys: ['checkout-flow', 'new-dashboard'], +}) +``` + +### Sending `$feature_flag_called` events + +Capturing `$feature_flag_called` events enables PostHog to know when a flag was accessed by a user and provide [analytics and insights](/docs/product-analytics/insights.md) on the flag. With `evaluateFlags()`, the SDK sends this event when you call `flags.isEnabled()` or `flags.getFlag()` for a flag. + +The SDK deduplicates these events per `(distinct_id, flag, value)` in a local cache. If you reinitialize the PostHog client, the cache resets and `$feature_flag_called` events may be sent again. PostHog handles duplicates, so duplicate `$feature_flag_called` events don't affect your analytics. + +`flags.getFlagPayload()` doesn't send `$feature_flag_called` events and doesn't count as an access for `onlyAccessed()`. + +### Advanced: Overriding server properties + +Sometimes, you may want to evaluate feature flags using [person properties](/docs/product-analytics/person-properties.md), [groups](/docs/product-analytics/group-analytics.md), or group properties that haven't been ingested yet, or were set incorrectly earlier. + +You can provide properties to evaluate the flag with by using the `person properties`, `groups`, and `group properties` arguments. PostHog will then use these values to evaluate the flag, instead of any properties currently stored on your PostHog server. + +For example: + +Node.js + +PostHog AI + +```javascript +const flags = await client.evaluateFlags('distinct_id_of_the_user', { + personProperties: { + property_name: 'value', + }, + groups: { + your_group_type: 'your_group_id', + another_group_type: 'your_group_id', + }, + groupProperties: { + your_group_type: { + group_property_name: 'value', + }, + another_group_type: { + group_property_name: 'value', + }, + }, +}) +if (flags.isEnabled('flag-key')) { + // Do something differently for this user +} +``` + +### Overriding GeoIP properties + +By default, a user's GeoIP properties are set using the IP address they use to capture events on the frontend. You may want to override the these properties when evaluating feature flags. A common reason to do this is when you're not using PostHog on your frontend, so the user has no GeoIP properties. + +You can override GeoIP properties by including them in the `person_properties` parameter when evaluating feature flags. This is useful when you're evaluating flags on your backend and want to use the client's location instead of your server's location. + +The following GeoIP properties can be overridden: + +- `$geoip_country_code` +- `$geoip_country_name` +- `$geoip_city_name` +- `$geoip_city_confidence` +- `$geoip_continent_code` +- `$geoip_continent_name` +- `$geoip_latitude` +- `$geoip_longitude` +- `$geoip_postal_code` +- `$geoip_subdivision_1_code` +- `$geoip_subdivision_1_name` +- `$geoip_subdivision_2_code` +- `$geoip_subdivision_2_name` +- `$geoip_subdivision_3_code` +- `$geoip_subdivision_3_name` +- `$geoip_time_zone` + +Simply include any of these properties in the `person_properties` parameter alongside your other person properties when calling feature flags. + +### Request timeout + +You can configure the `featureFlagsRequestTimeoutMs` parameter when initializing your PostHog client to set a flag request timeout. This helps prevent your code from being blocked if PostHog's servers are too slow to respond. By default, this is set to 3 seconds. + +JavaScript + +PostHog AI + +```javascript +const client = new PostHog('', { + host: 'https://us.i.posthog.com', + featureFlagsRequestTimeoutMs: 3000, // Time in milliseconds. Defaults to 3000 (3 seconds). +}) +``` + +> **Note:** For remote config flags, see the [remote config documentation](/docs/feature-flags/remote-config.md). Remote config requires the [Feature Flags secure API key](/docs/feature-flags/remote-config.md#step-1-find-your-feature-flags-secure-api-key) passed as the `personalApiKey` option. + +### Local evaluation + +Evaluating feature flags requires making a request to PostHog for each flag. However, you can improve performance by evaluating flags locally. Instead of making a request for each flag, PostHog will periodically request and store feature flag definitions locally, enabling you to evaluate flags without making additional requests. + +It is best practice to use local evaluation flags when possible, since this enables you to resolve flags faster and with fewer API calls. + +For details on how to implement local evaluation, see our [local evaluation guide](/docs/feature-flags/local-evaluation.md). + +Node.js + +PostHog AI + +```javascript +const flags = await client.evaluateFlags('user distinct id', { + groups: { organization: 'google' }, + groupProperties: { organization: { is_authorized: true } }, +}) +const flagValue = flags.getFlag('flag-key') +``` + +#### 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`: + +Node.js + +PostHog AI + +```javascript +await client.reloadFeatureFlags() +// Do something with feature flags here +``` + +#### Distributed environments + +In multi-worker or edge environments, you can implement custom caching for flag definitions using Redis, Cloudflare KV, or other storage backends. This enables sharing definitions across workers and coordinating fetches. See our guide for [local evaluation in distributed environments](/docs/feature-flags/local-evaluation/distributed-environments?tab=Node.js.md) for details. + +## Experiments (A/B tests) + +Since [experiments](/docs/experiments/start-here.md) use feature flags, the code for running an experiment is very similar to the feature flags code: + +Node.js + +PostHog AI + +```javascript +const flags = await client.evaluateFlags('user_distinct_id') +const variant = flags.getFlag('experiment-feature-flag-key') +if (variant === 'variant-name') { + // Do something +} +``` + +It's also possible to [run experiments without using feature flags](/docs/experiments/running-experiments-without-feature-flags.md). + +## Group analytics + +Group analytics enable you to associate an event with a group (e.g. teams, organizations, etc.). Read the [group analytics guide](/docs/product-analytics/group-analytics.md) for more information. + +To create a group or update its properties, use `groupIdentify`: + +Node.js + +PostHog AI + +```javascript +client.groupIdentify({ + groupType: 'company', + groupKey: 'company_id_in_your_db', + properties: { + name: 'Awesome Inc', + employees: 11, + }, + // optional distinct ID to associate event with an existing person + distinctId: 'xyz' +}) +``` + +`name` is a special property which is used in the PostHog UI for the name of the group. If you don't specify a `name` property, the group ID is used instead. + +If the optional `distinctId` parameter is not provided in the group identify call, it defaults to `${groupType}_${groupKey}` (e.g., `$company_company_id_in_your_db` in the example above). This default behavior results in each group appearing as a separate person in PostHog. To avoid this, it's often more practical to use a consistent `distinctId`, such as `group_identifier`. + +Once a group is created, you can use the `capture` method and pass in the `groups` parameter to capture an event with group analytics. + +Node.js + +PostHog AI + +```javascript +client.capture({ + event: 'some_event', + distinctId: 'user_distinct_id', + groups: { company: 'company_id_in_your_db' }, +}) +``` + +## GeoIP properties + +Before `posthog-node` v3.0, we added GeoIP properties to all incoming events by default. We also used these properties for feature flag evaluation, based on the IP address of the request. This isn't ideal since they are created based on your server IP address, rather than the user's, leading to incorrect location resolution. + +As of `posthog-node` v3.0, the default now is to disregard the server IP, not add the GeoIP properties, and not use the values for feature flag evaluations. + +You can go back to previous behavior by setting `disableGeoip` to false in your initialization: + +Node.js + +PostHog AI + +```javascript +const posthog = new PostHog('', { + host: 'https://us.i.posthog.com', + disableGeoip: false +}) +``` + +The list of properties that this overrides: + +1. `$geoip_city_name` +2. `$geoip_country_name` +3. `$geoip_country_code` +4. `$geoip_continent_name` +5. `$geoip_continent_code` +6. `$geoip_postal_code` +7. `$geoip_time_zone` + +You can also explicitly chose to enable or disable GeoIP for a single capture request like so: + +Node.js + +PostHog AI + +```javascript +client.capture({ + distinctId: distinctId, + event: 'your_event', + disableGeoip: `true`, +}) +``` + +## Shutdown + +You should call `shutdown` on your program's exit to exit cleanly: + +Node.js + +PostHog AI + +```javascript +// Stop pending pollers and flush any remaining events +await client.shutdown() +``` + +## Debug mode + +If you're not seeing the expected events being captured, the feature flags being evaluated, or the surveys being shown, you can enable debug mode to see what's happening. + +You can enable debug mode by calling the `debug()` method in your code. This will enable verbose logs about the inner workings of the SDK. + +Node.js + +PostHog AI + +```javascript +client.debug() +``` + +## Handling errors thrown by the SDK + +If you are experiencing issues with the SDK it could be a number of things from an incorrectly configured API key, to some other network related issues. + +The SDK does not throw errors for things happening in the background to ensure it doesn't affect your process. You can however hook into the errors to get more information: + +Node.js + +PostHog AI + +```javascript +client.on("error", (err) => { + // Whatever handling you want + console.error("PostHog had an error!", err) +}) +``` + +## Short-lived processes like serverless environments + +The Node SDK is designed to queue and batch requests in the background to optimize API calls and network time. As serverless environments like AWS Lambda or [Vercel Functions](/docs/libraries/vercel.md) are short-lived, we provide a few options to ensure all events are captured. + +First, we recommend using the `captureImmediate` method instead of `capture` to ensure the event is captured before the function shuts down. It guarantees the HTTP request finishes before your function continues (or shuts down). + +Second, we recommend setting `flushAt` to `1` and `flushInterval` to `0` to ensure the events are sent immediately. These set the queue to flush immediately, both in terms of events and time. + +Third, we provide a method `shutdown()` which can be awaited to ensure all queued events are sent to the API. For example: + +Node.js + +PostHog AI + +```javascript +export const handler() { + client.capture({ + distinctId: 'distinct_id_of_the_user', + event: 'thing_happened' + }) + client.capture({ + distinctId: 'distinct_id_of_the_user', + event: 'other_thing_happened' + }) + // So far 2 events are queued but not sent + // Calling shutdown, flushed the queue but batched into 1 API call for maximum efficiency + await client.shutdown() +} +``` + +This is also useful for shutting down a standard Node.js app. + +## AI Observability + +You can capture LLM usage and performance data by combining the `posthog-node` and `@posthog/ai` libraries. These work with LLM providers like OpenAI and Vercel's AI SDKs. Learn more in our [AI Observability docs](/docs/ai-observability.md). + +## Error tracking + +You can capture errors using the `posthog-node` library. This enables you to see stack traces, source code, and watch associated session recordings to improve your application stability. Learn more in our [error tracking docs](/docs/error-tracking/installation/node.md). + +## Upgrading from V1 to V2 + +V2.x.x of the Node.js library is completely rewritten in Typescript and is based on a new JS core shared with other JavaScript based libraries with the goal of ensuring new features and fixes reach the different libraries at the same pace. + +With the release of V2, the API was kept mostly the same but with some small changes and deprecations: + +1. The minimum PostHog version requirement is 1.38 +2. The `callback` parameter passed as an optional last argument to most of the methods is no longer supported +3. The method signature for `isFeatureEnabled` and `getFeatureFlag` is slightly modified. See the above documentation for each method for more details. +4. For specific changes, [see the CHANGELOG](https://github.com/PostHog/posthog-js/blob/main/packages/node/CHANGELOG.md) + +### Still have questions? + +Ask PostHog AI + +### Was this page useful? + +HelpfulCould be better \ No newline at end of file diff --git a/apps/basic-integration/javascript-node/native-http-contacts/.claude/skills/integration-javascript_node/references/posthog-node.md b/apps/basic-integration/javascript-node/native-http-contacts/.claude/skills/integration-javascript_node/references/posthog-node.md new file mode 100644 index 000000000..90dfb2eb7 --- /dev/null +++ b/apps/basic-integration/javascript-node/native-http-contacts/.claude/skills/integration-javascript_node/references/posthog-node.md @@ -0,0 +1,1590 @@ +> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt + +# PostHog Node.js SDK + +PostHog Node.js SDK allows you to capture events and send them to PostHog from your Node.js applications. + +## Categories + +- Initialization +- Identification +- Capture +- Error tracking +- Privacy +- Feature flags +- Context + +## PostHog + +### Other methods + +#### getLibraryId() + +**Release Tag:** public + +### Returns + +- `string` + +### Examples + +```node +// Generated example for getLibraryId +posthog.getLibraryId(); +``` + +--- + +#### enterContext() + +**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. + +### Parameters + +- **`data`** (`Partial`) - Context data to apply (distinctId, sessionId, properties) +- **`options?`** (`ContextOptions`) - Context options (fresh: true to start with clean context instead of inheriting) + +### Returns + +- `void` + +### Examples + +```node +// Generated example for enterContext +posthog.enterContext(); +``` + +--- + +#### flush() + +**Release Tag:** public + +### Returns + +- `Promise` + +### Examples + +```node +// Generated example for flush +posthog.flush(); +``` + +--- + +#### prepareEventMessage() + +**Release Tag:** public + +### Parameters + +- **`props`** (`EventMessage`) + +### Returns + +- `Promise<{ + distinctId: string; + event: string; + properties: PostHogEventProperties; + options: PostHogCaptureOptions; + }>` + +### Examples + +```node +// Generated example for prepareEventMessage +posthog.prepareEventMessage(); +``` + +--- + +#### fetch() + +**Release Tag:** public + +### Parameters + +- **`url`** (`string`) +- **`options`** (`PostHogFetchOptions`) + +### Returns + +- `Promise` + +### Examples + +```node +// Generated example for fetch +posthog.fetch(); +``` + +--- + +#### getSurveysStateless() + +**Release Tag:** public + +* ** SURVEYS * + +### Returns + +- `Promise` + +### Examples + +```node +// Generated example for getSurveysStateless +posthog.getSurveysStateless(); +``` + +--- + +#### on() + +**Release Tag:** public + +### Parameters + +- **`event`** (`string`) +- **`cb`** (`(...args: any[]) => void`) + +### Returns + +- `() => void` + +### Examples + +```node +// Generated example for on +posthog.on(); +``` + +--- + +#### optIn() + +**Release Tag:** public + +### Returns + +- `Promise` + +### Examples + +```node +// Generated example for optIn +posthog.optIn(); +``` + +--- + +#### optOut() + +**Release Tag:** public + +### Returns + +- `Promise` + +### Examples + +```node +// Generated example for optOut +posthog.optOut(); +``` + +--- + +#### register() + +**Release Tag:** public + +### Parameters + +- **`properties`** (`PostHogEventProperties`) + +### Returns + +- `Promise` + +### Examples + +```node +// Generated example for register +posthog.register(); +``` + +--- + +#### unregister() + +**Release Tag:** public + +### Parameters + +- **`property`** (`string`) + +### Returns + +- `Promise` + +### Examples + +```node +// Generated example for unregister +posthog.unregister(); +``` + +--- + +### Initialization methods + +#### PostHog() + +**Release Tag:** public + +Initialize a new PostHog client instance. + +### Parameters + +- **`apiKey`** (`string`) - Your PostHog project API key +- **`options?`** (`PostHogOptions`) - Configuration options for the client + +### Returns + +- `any` + +### Examples + +#### Basic initialization + +```node +// Basic initialization +const client = new PostHogBackendClient( + 'your-api-key', + { host: 'https://app.posthog.com' } +) +``` + +#### With a secret key (Personal API Key or Project Secret API Key) for local evaluation + +```node +// With a secret key (Personal API Key or Project Secret API Key) for local evaluation +const client = new PostHogBackendClient( + 'your-api-key', + { + host: 'https://app.posthog.com', + secretKey: 'your-secret-key' + } +) +``` + +--- + +#### debug() + +**Release Tag:** public + +Enable or disable debug logging. + +### Parameters + +- **`enabled?`** (`boolean`) - Whether to enable debug logging + +### Returns + +- `void` + +### Examples + +#### Enable debug logging + +```node +// Enable debug logging +client.debug(true) +``` + +#### Disable debug logging + +```node +// Disable debug logging +client.debug(false) +``` + +--- + +#### getLibraryVersion() + +**Release Tag:** public + +Get the library version from package.json. + +### Returns + +- `string` + +### Examples + +```node +// Get version +const version = client.getLibraryVersion() +console.log(`Using PostHog SDK version: ${version}`) +``` + +--- + +#### getPersistedProperty() + +**Release Tag:** public + +Get a persisted property value from memory storage. + +### Parameters + +- **`key`** (`PostHogPersistedProperty`) - The property key to retrieve + +### Returns + +**Union of:** +- `any` +- `undefined` + +### Examples + +#### Get user ID + +```node +// Get user ID +const userId = client.getPersistedProperty('userId') +``` + +#### Get session ID + +```node +// Get session ID +const sessionId = client.getPersistedProperty('sessionId') +``` + +--- + +#### setPersistedProperty() + +**Release Tag:** public + +Set a persisted property value in memory storage. + +### Parameters + +- **`key`** (`PostHogPersistedProperty`) - The property key to set +- **`value`** (`any | null`) - The value to store (null to remove) + +### Returns + +- `void` + +### Examples + +#### Set user ID + +```node +// Set user ID +client.setPersistedProperty('userId', 'user_123') +``` + +#### Set session ID + +```node +// Set session ID +client.setPersistedProperty('sessionId', 'session_456') +``` + +--- + +#### shutdown() + +**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. + +### Parameters + +- **`shutdownTimeoutMs?`** (`number`) - Maximum time to wait for shutdown in milliseconds + +### Returns + +- `Promise` + +### Examples + +```node +// shutdown before process exit +process.on('SIGINT', async () => { + await posthog.shutdown() + process.exit(0) +}) +``` + +--- + +### Identification methods + +#### alias() + +**Release Tag:** public + +Create an alias to link two distinct IDs together. + +### Parameters + +- **`data`** (`{ + distinctId: string; + alias: string; + disableGeoip?: boolean; + }`) - The alias data containing distinctId and alias + +### Returns + +- `void` + +### Examples + +```node +// Link an anonymous user to an identified user +client.alias({ + distinctId: 'anonymous_123', + alias: 'user_456' +}) +``` + +--- + +#### aliasImmediate() + +**Release Tag:** public + +Create an alias to link two distinct IDs together immediately (synchronously). + +### Parameters + +- **`data`** (`{ + distinctId: string; + alias: string; + disableGeoip?: boolean; + }`) - The alias data containing distinctId and alias + +### Returns + +- `Promise` + +### Examples + +```node +// Link an anonymous user to an identified user immediately +await client.aliasImmediate({ + distinctId: 'anonymous_123', + alias: 'user_456' +}) +``` + +--- + +#### getCustomUserAgent() + +**Release Tag:** public + +Get the custom user agent string for this client. + +### Returns + +- `string` + +### Examples + +```node +// Get user agent +const userAgent = client.getCustomUserAgent() +// Returns: "posthog-node/5.7.0" +``` + +--- + +#### groupIdentify() + +**Release Tag:** public + +Create or update a group and its properties. + +### Parameters + +- **`{ groupType, groupKey, properties, distinctId, disableGeoip }`** (`any`) +- **`input`** (`GroupIdentifyMessage`) + +### Returns + +- `void` + +### Examples + +#### Create a company group + +```node +// 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 + +```node +// Update organization properties +client.groupIdentify({ + groupType: 'organization', + groupKey: 'org-456', + properties: { + plan: 'enterprise', + region: 'US-West' + } +}) +``` + +--- + +#### groupIdentifyImmediate() + +**Release Tag:** public + +Create or update a group and its properties immediately (synchronously). + +### Parameters + +- **`{ groupType, groupKey, properties, distinctId, disableGeoip, }`** (`any`) +- **`input`** (`GroupIdentifyMessage`) + +### Returns + +- `Promise` + +### Examples + +```node +// Immediately create or update a company group +await client.groupIdentifyImmediate({ + groupType: 'company', + groupKey: 'acme-corp', + properties: { + name: 'Acme Corporation', + industry: 'Technology', + employee_count: 500 + } +}) +``` + +--- + +#### identify() + +**Release Tag:** public + +Identify a user and set their properties. + +### Parameters + +- **`{ distinctId, properties, disableGeoip }`** (`any`) +- **`input`** (`IdentifyMessage`) + +### Returns + +- `void` + +### Examples + +#### Basic identify with properties + +```node +// Basic identify with properties +client.identify({ + distinctId: 'user_123', + properties: { + name: 'John Doe', + email: 'john@example.com', + plan: 'premium' + } +}) +``` + +#### Using $set and $set_once + +```node +// 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' + } +}) +``` + +--- + +#### identifyImmediate() + +**Release Tag:** public + +Identify a user and set their properties immediately (synchronously). + +### Parameters + +- **`{ distinctId, properties, disableGeoip }`** (`any`) +- **`input`** (`IdentifyMessage`) + +### Returns + +- `Promise` + +### Examples + +```node +// Basic immediate identify +await client.identifyImmediate({ + distinctId: 'user_123', + properties: { + name: 'John Doe', + email: 'john@example.com' + } +}) +``` + +--- + +#### setPersonProperties() + +**Release Tag:** public + +Set properties on a person profile. + +### Parameters + +- **`{ distinctId, properties, propertiesOnce }`** (`any`) +- **`input`** (`SetPersonPropertiesMessage`) + +### Returns + +- `void` + +### Examples + +```node +client.setPersonProperties({ + distinctId: 'user_123', + properties: { plan: 'premium' }, + propertiesOnce: { first_seen: '2026-06-15' } +}) +``` + +--- + +#### unsetPersonProperties() + +**Release Tag:** public + +Remove properties from a person profile. + +### Parameters + +- **`{ distinctId, properties }`** (`any`) +- **`input`** (`UnsetPersonPropertiesMessage`) + +### Returns + +- `void` + +### Examples + +```node +client.unsetPersonProperties({ + distinctId: 'user_123', + properties: ['plan', 'email'] +}) +``` + +--- + +### Capture methods + +#### capture() + +**Release Tag:** public + +Capture an event manually. + +### Parameters + +- **`props`** (`EventMessage`) - The event properties + +### Returns + +- `void` + +### Examples + +```node +// Basic capture +client.capture({ + distinctId: 'user_123', + event: 'button_clicked', + properties: { button_color: 'red' } +}) +``` + +--- + +#### captureAi() + +**Release Tag:** public + +Capture an AI event on the dedicated AI capture endpoint. +Beta: the signature is stable; operational limits (per-event size cap, batching, endpoint) may change without notice. Delivery is async, and no redaction or truncation is applied to the payload. + +### Parameters + +- **`props`** (`EventMessage`) - The event properties + +### Returns + +**Union of:** +- `string` +- `undefined` + +### Examples + +```node +// Generated example for captureAi +posthog.captureAi(); +``` + +--- + +#### captureAiImmediate() + +**Release Tag:** public + +Capture an AI event on the dedicated AI capture endpoint, resolving after the send completes. Use in short-lived processes (serverless) where the runtime may freeze before a background flush runs. + +### Parameters + +- **`props`** (`EventMessage`) - The event properties + +### Returns + +**Union of:** +- `Promise` + +### Examples + +```node +// Generated example for captureAiImmediate +posthog.captureAiImmediate(); +``` + +--- + +#### captureImmediate() + +**Release Tag:** public + +Capture an event immediately (synchronously). + +### Parameters + +- **`props`** (`EventMessage`) - The event properties + +### Returns + +- `Promise` + +### Examples + +#### Basic immediate capture + +```node +// Basic immediate capture +await client.captureImmediate({ + distinctId: 'user_123', + event: 'button_clicked', + properties: { button_color: 'red' } +}) +``` + +#### With feature flags + +```node +// With feature flags +await client.captureImmediate({ + distinctId: 'user_123', + event: 'user_action', + sendFeatureFlags: true +}) +``` + +#### With custom feature flags options + +```node +// 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'] + } +}) +``` + +--- + +### Error tracking methods + +#### captureException() + +**Release Tag:** public + +Capture an error exception as an event. + +### Parameters + +- **`error`** (`unknown`) - The error to capture +- **`distinctId?`** (`string`) - Optional user distinct ID +- **`additionalProperties?`** (`Record`) - Optional additional properties to include +- **`uuid?`** (`EventMessage['uuid']`) - Optional event UUID +- **`flags?`** (`FeatureFlagEvaluations`) - Optional `FeatureFlagEvaluations` snapshot to attach the same flag context as your other events + +### Returns + +- `void` + +### Examples + +#### Capture an error with user ID + +```node +// Capture an error with user ID +try { + // Some risky operation + riskyOperation() +} catch (error) { + client.captureException(error, 'user_123') +} +``` + +#### Capture with additional properties + +```node +// Capture with additional properties +try { + apiCall() +} catch (error) { + client.captureException(error, 'user_123', { + endpoint: '/api/users', + method: 'POST', + status_code: 500 + }) +} +``` + +--- + +#### captureExceptionImmediate() + +**Release Tag:** public + +Capture an error exception as an event immediately (synchronously). + +### Parameters + +- **`error`** (`unknown`) - The error to capture +- **`distinctId?`** (`string`) - Optional user distinct ID +- **`additionalProperties?`** (`Record`) - Optional additional properties to include +- **`flags?`** (`FeatureFlagEvaluations`) - Optional `FeatureFlagEvaluations` snapshot to attach the same flag context as your other events + +### Returns + +- `Promise` + +### Examples + +#### Capture an error immediately with user ID + +```node +// Capture an error immediately with user ID +try { + // Some risky operation + riskyOperation() +} catch (error) { + await client.captureExceptionImmediate(error, 'user_123') +} +``` + +#### Capture with additional properties + +```node +// Capture with additional properties +try { + apiCall() +} catch (error) { + await client.captureExceptionImmediate(error, 'user_123', { + endpoint: '/api/users', + method: 'POST', + status_code: 500 + }) +} +``` + +--- + +### Privacy methods + +#### disable() + +**Release Tag:** public + +Disable the PostHog client (opt-out). + +### Returns + +- `Promise` + +### Examples + +```node +// Disable client +await client.disable() +// Client is now disabled and will not capture events +``` + +--- + +#### enable() + +**Release Tag:** public + +Enable the PostHog client (opt-in). + +### Returns + +- `Promise` + +### Examples + +```node +// Enable client +await client.enable() +// Client is now enabled and will capture events +``` + +--- + +### Feature flags methods + +#### evaluateFlags() + +**Release 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`. A requested key missing from local definitions is included in a `/flags` fallback unless `onlyEvaluateLocally` is true. Locally resolved values remain authoritative when remote results are merged. In particular, a cached inactive definition is a conclusive `false` result locally, while remote evaluation omits globally inactive flags and therefore leaves those keys absent. +**Trim the request.** Pass `flagKeys` to scope local evaluation, the underlying `/flags` request, and the returned snapshot to a subset of flags. Remote evaluation responses are not cached, so a key missing both locally and remotely costs one `/flags` request per `evaluateFlags()` call. +**Trim the event payload.** Use `flags.only([...])` or `flags.onlyAccessed()` to filter which flags get attached to a captured event without re-fetching. + +### Parameters + +- **`options?`** (`AllFlagsOptions`) - Optional configuration for flag evaluation. Supports the same fields as `getAllFlags()`. `flagKeys` scopes local evaluation, the `/flags` request, and the returned snapshot. `onlyEvaluateLocally` prevents fallback and leaves unresolved keys absent. + +### Returns + +- `Promise` + +### Examples + +#### + +```node +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 }) +``` + +#### + +```node +Scope the request to specific keys: + +const flags = await client.evaluateFlags('user_123', { + flagKeys: ['new-dashboard', 'checkout-flow'], + personProperties: { plan: 'enterprise' }, +}) +``` + +#### + +```node +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() }) +``` + +#### + +```node +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 }) +}) +``` + +--- + +#### getAllFlags() + +**Release Tag:** public + +Get all feature flag values for a specific user. + +### Parameters + +- **`options?`** (`AllFlagsOptions`) - Optional configuration for flag evaluation + +### Returns + +- `Promise>` + +### Examples + +#### Get all flags for a user + +```node +// 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 + +```node +// With specific flag keys +const specificFlags = await client.getAllFlags('user_123', { + flagKeys: ['flag-1', 'flag-2'] +}) +``` + +#### With groups and properties + +```node +// With groups and properties +const orgFlags = await client.getAllFlags('user_123', { + groups: { organization: 'acme-corp' }, + personProperties: { plan: 'enterprise' } +}) +``` + +--- + +#### getAllFlagsAndPayloads() + +**Release Tag:** public + +Get all feature flag values and payloads for a specific user. + +### Parameters + +- **`options?`** (`AllFlagsOptions`) - Optional configuration for flag evaluation + +### Returns + +- `Promise` + +### Examples + +#### Get all flags and payloads for a user + +```node +// 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 + +```node +// With specific flag keys +const result = await client.getAllFlagsAndPayloads('user_123', { + flagKeys: ['flag-1', 'flag-2'] +}) +``` + +#### Only evaluate locally + +```node +// Only evaluate locally +const result = await client.getAllFlagsAndPayloads('user_123', { + onlyEvaluateLocally: true +}) +``` + +--- + +#### getFeatureFlag() + +**Release Tag:** deprecated + +Get the value of a feature flag for a specific user. +A boolean `false` is a conclusive off evaluation. `undefined` means no result is available, for example because the key was not returned or local-only evaluation was inconclusive. Local evaluation resolves cached inactive definitions to `false`; remote evaluation omits globally inactive flags, so the result depends on which evaluation path is available. + +### Parameters + +- **`key`** (`string`) - The feature flag key +- **`distinctId`** (`string`) - The user's distinct ID +- **`options?`** (`{ + groups?: Record; + personProperties?: Properties; + groupProperties?: Record; + onlyEvaluateLocally?: boolean; + sendFeatureFlagEvents?: boolean; + disableGeoip?: boolean; + }`) - Optional configuration for flag evaluation + +### Returns + +**Union of:** +- `Promise` + +### Examples + +#### Basic feature flag check + +```node +// 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 evaluated off, or no value was returned +} +``` + +#### With groups and properties + +```node +// 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 + +```node +// Only evaluate locally +const flagValue = await client.getFeatureFlag('local-flag', 'user_123', { + onlyEvaluateLocally: true +}) +``` + +--- + +#### getFeatureFlagPayload() + +**Release Tag:** deprecated + +Get the payload for a feature flag. + +### Parameters + +- **`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; + personProperties?: Properties; + groupProperties?: Record; + onlyEvaluateLocally?: boolean; + sendFeatureFlagEvents?: boolean; + disableGeoip?: boolean; + }`) - Optional configuration for flag evaluation + +### Returns + +**Union of:** +- `Promise` + +### Examples + +#### Get payload for a feature flag + +```node +// 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 + +```node +// Get payload with specific match value +const payload = await client.getFeatureFlagPayload('flag-key', 'user_123', 'variant-a') +``` + +#### With groups and properties + +```node +// With groups and properties +const payload = await client.getFeatureFlagPayload('org-flag', 'user_123', undefined, { + groups: { organization: 'acme-corp' }, + personProperties: { plan: 'enterprise' } +}) +``` + +--- + +#### getFeatureFlagResult() + +**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. A result with `enabled: false` is a conclusive off evaluation; `undefined` means no evaluation is available. Local evaluation resolves cached inactive definitions to `enabled: false`, while remote evaluation omits globally inactive flags. + +### Parameters + +- **`key`** (`string`) - The feature flag key +- **`options?`** (`FlagEvaluationOptions`) - Optional configuration for flag evaluation + +### Returns + +**Union of:** +- `Promise` + +### Examples + +#### Get flag result + +```node +// 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 + +```node +// With groups and properties +const result = await client.getFeatureFlagResult('org-feature', 'user_123', { + groups: { organization: 'acme-corp' }, + personProperties: { plan: 'enterprise' } +}) +``` + +--- + +#### getRemoteConfigPayload() + +**Release Tag:** public + +Get the remote config payload for a feature flag. + +### Parameters + +- **`flagKey`** (`string`) - The feature flag key + +### Returns + +**Union of:** +- `Promise` + +### Examples + +```node +// Get remote config payload +const payload = await client.getRemoteConfigPayload('flag-key') +if (payload) { + console.log('Remote config payload:', payload) +} +``` + +--- + +#### isFeatureEnabled() + +**Release Tag:** deprecated + +Check if a feature flag is enabled for a specific user. + +### Parameters + +- **`key`** (`string`) - The feature flag key +- **`distinctId`** (`string`) - The user's distinct ID +- **`options?`** (`{ + groups?: Record; + personProperties?: Properties; + groupProperties?: Record; + onlyEvaluateLocally?: boolean; + sendFeatureFlagEvents?: boolean; + disableGeoip?: boolean; + }`) - Optional configuration for flag evaluation + +### Returns + +**Union of:** +- `Promise` + +### Examples + +#### Basic feature flag check + +```node +// 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 { + // Flag evaluated off, or no value was returned + console.log('New feature is not active') +} +``` + +#### With groups and properties + +```node +// With groups and properties +const isEnabled = await client.isFeatureEnabled('org-feature', 'user_123', { + groups: { organization: 'acme-corp' }, + personProperties: { plan: 'enterprise' } +}) +``` + +--- + +#### isLocalEvaluationReady() + +**Release Tag:** public + +Check if local evaluation of feature flags is ready. + +### Returns + +- `boolean` + +### Examples + +```node +// 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') +} +``` + +--- + +#### overrideFeatureFlags() + +**Release Tag:** public + +Override feature flags locally. Useful for testing and local development. Overridden flags take precedence over both local evaluation and remote evaluation. + +### Parameters + +- **`overrides`** (`OverrideFeatureFlagsOptions`) - Flag overrides configuration + +### Returns + +- `void` + +### Examples + +```node +// 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 } } +}) +``` + +--- + +#### reloadFeatureFlags() + +**Release Tag:** public + +Reload feature flag definitions from the server for local evaluation. + +### Returns + +- `Promise` + +### Examples + +#### Force reload of feature flags + +```node +// Force reload of feature flags +await client.reloadFeatureFlags() +console.log('Feature flags reloaded') +``` + +#### Reload before checking a specific flag + +```node +// Reload before checking a specific flag +await client.reloadFeatureFlags() +const flag = await client.getFeatureFlag('flag-key', 'user_123') +``` + +--- + +#### waitForLocalEvaluationReady() + +**Release Tag:** public + +Wait for local evaluation of feature flags to be ready. + +### Parameters + +- **`timeoutMs?`** (`number`) - Timeout in milliseconds (default: 30000) + +### Returns + +- `Promise` + +### Examples + +#### Wait for local evaluation + +```node +// 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 + +```node +// Wait with custom timeout +const isReady = await client.waitForLocalEvaluationReady(10000) // 10 seconds +``` + +--- + +### Context methods + +#### getContext() + +**Release Tag:** public + +Get the current context data. + +### Returns + +**Union of:** +- `ContextData` +- `undefined` + +### Examples + +```node +// Get current context within a withContext block +posthog.withContext({ distinctId: 'user_123' }, () => { + const context = posthog.getContext() + console.log(context?.distinctId) // 'user_123' +}) +``` + +--- + +#### withContext() + +**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. + +### Parameters + +- **`data`** (`Partial`) - Context data to apply (sessionId, distinctId, properties, enableExceptionAutocapture) +- **`fn`** (`() => T`) - Function to run with the context +- **`options?`** (`ContextOptions`) - Context options (fresh: true to start with clean context instead of inheriting) + +### Returns + +- `T` + +### Examples + +```node +posthog.withContext({ distinctId: 'user_123' }, () => { + posthog.capture({ event: 'button clicked' }) +}) +``` + +--- \ No newline at end of file diff --git a/apps/basic-integration/javascript-node/native-http-contacts/.env.example b/apps/basic-integration/javascript-node/native-http-contacts/.env.example new file mode 100644 index 000000000..bb891b097 --- /dev/null +++ b/apps/basic-integration/javascript-node/native-http-contacts/.env.example @@ -0,0 +1,2 @@ +POSTHOG_PROJECT_TOKEN= +POSTHOG_HOST= diff --git a/apps/basic-integration/javascript-node/native-http-contacts/index.js b/apps/basic-integration/javascript-node/native-http-contacts/index.js index 0ef675101..9cc963d5a 100644 --- a/apps/basic-integration/javascript-node/native-http-contacts/index.js +++ b/apps/basic-integration/javascript-node/native-http-contacts/index.js @@ -1,4 +1,5 @@ import { createServer } from 'node:http'; +import { posthog } from './posthog.js'; const contacts = []; const groups = [{ id: 1, name: 'All Contacts' }]; @@ -47,6 +48,12 @@ const server = createServer(async (req, res) => { const group = { id: nextGroupId++, name: body.name }; groups.push(group); + if (posthog) { + posthog.capture({ + event: 'group_created', + properties: { group_id: group.id }, + }); + } return json(res, 201, group); } @@ -90,6 +97,17 @@ const server = createServer(async (req, res) => { created_at: new Date().toISOString(), }; contacts.push(contact); + if (posthog) { + posthog.capture({ + event: 'contact_created', + properties: { + contact_id: contact.id, + group_id: contact.group_id, + has_phone: Boolean(contact.phone), + has_company: Boolean(contact.company), + }, + }); + } return json(res, 201, contact); } @@ -108,12 +126,25 @@ const server = createServer(async (req, res) => { if (!contact) return json(res, 404, { error: 'Contact not found' }); const body = await parseBody(req); + const updated_fields = Object.keys(body).filter((field) => + ['name', 'email', 'phone', 'company', 'group_id'].includes(field) + ); if (body.name !== undefined) contact.name = body.name; if (body.email !== undefined) contact.email = body.email; if (body.phone !== undefined) contact.phone = body.phone; if (body.company !== undefined) contact.company = body.company; if (body.group_id !== undefined) contact.group_id = body.group_id; + if (posthog) { + posthog.capture({ + event: 'contact_updated', + properties: { + contact_id: contact.id, + group_id: contact.group_id, + updated_fields, + }, + }); + } return json(res, 200, contact); } @@ -123,13 +154,25 @@ const server = createServer(async (req, res) => { const index = contacts.findIndex((c) => c.id === parseInt(deleteMatch[1], 10)); if (index === -1) return json(res, 404, { error: 'Contact not found' }); - contacts.splice(index, 1); + const [contact] = contacts.splice(index, 1); + if (posthog) { + posthog.capture({ + event: 'contact_deleted', + properties: { + contact_id: contact.id, + group_id: contact.group_id, + }, + }); + } res.writeHead(204); return res.end(); } json(res, 404, { error: 'Not found' }); } catch (err) { + if (posthog) { + posthog.captureException(err); + } json(res, 500, { error: 'Internal server error' }); } }); diff --git a/apps/basic-integration/javascript-node/native-http-contacts/package-lock.json b/apps/basic-integration/javascript-node/native-http-contacts/package-lock.json new file mode 100644 index 000000000..e82118d1f --- /dev/null +++ b/apps/basic-integration/javascript-node/native-http-contacts/package-lock.json @@ -0,0 +1,63 @@ +{ + "name": "native-http-contacts", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "native-http-contacts", + "version": "1.0.0", + "dependencies": { + "dotenv": "^17.4.2", + "posthog-node": "^5.51.8" + } + }, + "node_modules/@posthog/core": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/@posthog/core/-/core-1.52.0.tgz", + "integrity": "sha512-pvbdeRRpizktmo8MXZQxjAI4aFfNajwkzxbm72wKV9n2wWcnQWa4m+AqTI2zmmCSsYk7F666rRUdvYqZLjjhWg==", + "license": "MIT", + "dependencies": { + "@posthog/types": "^1.409.4" + } + }, + "node_modules/@posthog/types": { + "version": "1.410.0", + "resolved": "https://registry.npmjs.org/@posthog/types/-/types-1.410.0.tgz", + "integrity": "sha512-741sltt/h+l0eYH+Nkow96qKfDmRxwKacfjF93Z+kMySjzL0a87ptmpklZxGkbjBp/DJH/CSowGrolYWK/1ToA==", + "license": "MIT" + }, + "node_modules/dotenv": { + "version": "17.4.2", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.4.2.tgz", + "integrity": "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/posthog-node": { + "version": "5.51.8", + "resolved": "https://registry.npmjs.org/posthog-node/-/posthog-node-5.51.8.tgz", + "integrity": "sha512-TCqgAYbACwb/D3VI2S861ugD+FavvowQfak8eMwS/wATS+g0Wj+YpsABrBEKi+ZP3Y5SJDcoc7bIH49rlGo1Ww==", + "license": "MIT", + "dependencies": { + "@posthog/core": "^1.51.1" + }, + "engines": { + "node": "^20.20.0 || >=22.22.0" + }, + "peerDependencies": { + "rxjs": "^7.0.0" + }, + "peerDependenciesMeta": { + "rxjs": { + "optional": true + } + } + } + } +} diff --git a/apps/basic-integration/javascript-node/native-http-contacts/package.json b/apps/basic-integration/javascript-node/native-http-contacts/package.json index ff02a6c06..1d6efc169 100644 --- a/apps/basic-integration/javascript-node/native-http-contacts/package.json +++ b/apps/basic-integration/javascript-node/native-http-contacts/package.json @@ -8,5 +8,8 @@ "start": "node index.js", "dev": "node --watch index.js" }, - "dependencies": {} + "dependencies": { + "dotenv": "^17.4.2", + "posthog-node": "^5.51.8" + } } diff --git a/apps/basic-integration/javascript-node/native-http-contacts/posthog.js b/apps/basic-integration/javascript-node/native-http-contacts/posthog.js new file mode 100644 index 000000000..2d43993b3 --- /dev/null +++ b/apps/basic-integration/javascript-node/native-http-contacts/posthog.js @@ -0,0 +1,19 @@ +import 'dotenv/config'; +import { PostHog } from 'posthog-node'; + +const projectToken = process.env.POSTHOG_PROJECT_TOKEN; +const host = process.env.POSTHOG_HOST; + +if ((!projectToken || !host) && process.env.NODE_ENV !== 'production') { + const missingVariable = !projectToken ? 'POSTHOG_PROJECT_TOKEN' : 'POSTHOG_HOST'; + throw new Error( + `${missingVariable} variable required by PostHog is missing or un-configured, this causes events to be silently missed. This error stops appearing once ${missingVariable} is configured` + ); +} + +export const posthog = projectToken && host + ? new PostHog(projectToken, { + host, + enableExceptionAutocapture: true, + }) + : undefined;