PostHog Node.js SDK 6.x

Getting started

The Node.js SDK runs on your server, on Node.js 20 or later.

To send your first event, install posthog-node, create one client with your project token and host from your project settings, and call capture with a distinctId and an event name.

The client queues events and sends them in batches, so call shutdown before your process exits, or the last events are lost.

Install

Terminal
npm install posthog-node@~6.0

Initialize

TypeScript
import { PostHog } from 'posthog-node'
const client = new PostHog('<ph_project_api_key>', { host: 'https://us.i.posthog.com' })

Capture an event

TypeScript
client.capture({ distinctId: 'user_123', event: 'signed_up', properties: { plan: 'pro' } })

Shut down

Flush queued events before the process exits.

TypeScript
await client.shutdown()

Share context across calls

Wrap a request or job in withContext() so telemetry inside shares user and session state across function calls and await. This is useful inside API route controller code, tagging each request's downstream calls with the same session, user, and other metadata.

TypeScript
await client.withContext(
{ distinctId: 'user_123', sessionId: '0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b', properties: { plan: 'pro' } },
async () => {
// Other downstream calls
client.capture({ event: 'order_placed' })
}
)

Populate context in frameworks

Some frameworks can help you populate request context automatically from incoming headers:

  • Express. Call setupExpressRequestContext(client, app) before your routes, and setupExpressErrorHandler(client, app) after them.
  • NestJS. Register PostHogInterceptor from posthog-node/nestjs globally.
  • Hono and Fetch. Wrap handlers with posthogHonoMiddleware(client) or instrumentRequest(client, request, handler).

Calls inside withContext() inherit these fields by telemetry type:

TelemetryInherited from context
Events and exceptionsdistinctId, sessionId ($session_id, except groupIdentify), properties, options
Logs and spansdistinctId, sessionId
Feature flags (evaluateFlags, getAllFlags, getAllFlagsAndPayloads, getFeatureFlagResult)distinctId when omitted

Tracing headers are untrusted client data, never authentication. Pass an authenticated distinctId explicitly for authorization or sensitive decisions.

Flush in short-lived runtimes

Serverless Node runtimes (AWS Lambda, Vercel Functions) can freeze as soon as a handler returns. Reuse a module-scope client across calls and await client.flush() before returning, or pass waitUntil in PostHogOptions.

flush() has no overall timeout and never rejects, so race it against your remaining handler time. Save shutdown() for process exit, since it tears down flag polling, exception autocapture, and email sending.

On Cloudflare Workers and edge runtimes (posthog-node/edge), create a client per request with flushAt: 1, flushInterval: 0, and waitUntil: ctx.waitUntil.bind(ctx). The edge entrypoint has no AsyncLocalStorage, so withContext() doesn't propagate IDs and withSpan() doesn't nest across await. Pass distinctId and { parent: span } explicitly instead.

Handle background errors

Background batching, flag polling, and remote config calls never throw into your request path. Listen on the 'error' event to catch CaptureError, RemoteConfigPayloadError, and network failures:

TypeScript
client.on('error', (err) => {
console.error('PostHog error:', err)
})

Setup

new PostHog(...)

new PostHog(apiKey, options?): PostHog

Create a PostHog server client (import { PostHog } from 'posthog-node').

Keep one client for your server's lifetime and call await client.shutdown() on exit. For serverless handlers, reuse a module-scope client and call await client.flush(), or pass waitUntil in PostHogOptions.

Passing an empty apiKey or a phx_... personal API key logs one error and disables the client (isDisabled === true). Passing a phc_... project token as secretKey throws an Error.

Know what to await

CallMethodsReach for it when
Don't awaitcapture, captureAi, identify, alias, groupIdentify, setPersonProperties, unsetPersonProperties, captureException, captureLog, logger.*Queueing telemetry in memory on the request path without waiting on HTTP
awaitcaptureImmediate, captureAiImmediate, identifyImmediate, aliasImmediate, groupIdentifyImmediate, captureExceptionImmediateWaiting for an upload attempt to finish before a short-lived handler exits
awaitevaluateFlags, getFeatureFlagResult, getAllFlags, getAllFlagsAndPayloads, getRemoteConfigPayload, flush, shutdown, reloadFeatureFlags, waitForLocalEvaluationReadyReading flags, remote config, or draining queues
await ({ data, error })emails.send, emails.get, emails.setPreferencesSending transactional email or updating preferences (never rejects)

Parameters

ParameterTypeDescription
apiKeystringYour PostHog project API key (phc_...)
options?PostHogOptionsConfiguration options for the client

Returns

PostHog

Examples

TypeScript
// Basic initialization
import { PostHog } from 'posthog-node'
const client = new PostHog('<ph_project_api_key>', {
host: 'https://us.i.posthog.com',
})
TypeScript
// With a secret key (Project Secret API Key or Personal API Key) for local evaluation and emails
const client = new PostHog('<ph_project_api_key>', {
host: 'https://us.i.posthog.com',
secretKey: 'phs_...',
})

Capture

PostHog.capture

capture(props): void

Queue an event in memory to send asynchronously without blocking the caller.

Events with a distinctId (explicit or from withContext()) create or update person profiles by default unless options.process_person_profile is false on the call, in withContext(), or via registerOptions(). Pass $set and $set_once inside properties to set person properties, pass groups (such as { company: 'acme' }) to link groups, or send event: '$pageview' with $current_url for backend-only pageviews.

Omitting distinctId outside an identified context generates a UUIDv7 and sends a personless event (options: { process_person_profile: false }). Pass options: { process_person_profile: false } to send a personless event for a known distinctId.

Pass flags from evaluateFlags() to attach evaluated flags without extra requests. Use captureException() instead of capture({ event: '$exception' }), and don't mix capture() with captureImmediate() when event order matters.

Parameters

ParameterTypeDescription
propsEventMessageThe event payload

Returns

void

void

Examples

TypeScript
// Basic capture with person properties and groups
client.capture({
distinctId: 'user_123',
event: 'movie_played',
properties: {
movie_id: '123',
$set: { name: 'Max Hedgehog' },
$set_once: { initial_url: '/blog' },
},
groups: { company: 'acme' },
})
TypeScript
// Personless event for a known user
client.capture({
distinctId: 'user_123',
event: 'background_job',
options: { process_person_profile: false },
})

PostHog.captureImmediate

captureImmediate(props): Promise<void>

Send an event immediately and wait for the HTTP send attempt to settle.

Use in short-lived runtimes where the process can freeze before a background flush. Follows the same distinctId, person-profile, properties, groups, and flags rules as capture(), and shouldn't be mixed with queued capture() calls when order matters.

Parameters

ParameterTypeDescription
propsEventMessageThe event payload

Returns

Promise<void>

Promise that resolves when the send attempt completes

Examples

TypeScript
// Basic immediate capture
await client.captureImmediate({
distinctId: 'user_123',
event: 'button_clicked',
properties: { button_color: 'red' },
})
TypeScript
// With an evaluated flags snapshot
const flags = await client.evaluateFlags('user_123')
await client.captureImmediate({
distinctId: 'user_123',
event: 'user_action',
flags,
})
TypeScript
// Personless immediate capture
await client.captureImmediate({
distinctId: 'user_123',
event: 'webhook_received',
options: { process_person_profile: false },
})

CaptureError

Surfaced on the client error channel whenever a capture batch did not fully deliver: some events were dropped, some retry events outlived the attempt budget, or the batch hit a terminal transport/HTTP/parse failure.

A 2xx with drops is still a partial failure and is reported here — a successful HTTP status does not mean every event was accepted.

Extends

  • Error

Constructors

Constructor

new CaptureError(options): CaptureError

Parameters
ParameterType
optionsCaptureErrorParams
Returns

CaptureError

Properties

PropertyModifierTypeOverrides
cause?publicunknownError.cause
dropsreadonlyCaptureDroppedEvent[]-
endpointreadonlyCaptureEndpoint-
namepublicstringError.name
requestIdreadonlystring-
retryExhaustedreadonlystring[]-

Identify

PostHog.identify

identify(data): void

Queue an $identify event setting person properties for distinctId.

Use the same distinctId your frontend passes to posthog.identify() so server events, session replays, error tracking, and traces link to one person. Server identify() holds no ambient anonymous ID and only merges one when $anon_distinct_id is passed in properties.

Prefer $set or $set_once on capture() (or setPersonProperties()) when you only need to update properties without linking an anonymous ID.

Parameters

ParameterTypeDescription
dataIdentifyMessageThe identify payload containing distinctId and properties

Returns

void

Examples

TypeScript
// Basic identify with properties
client.identify({
distinctId: 'user_123',
properties: {
name: 'John Doe',
email: 'john@example.com',
plan: 'premium',
},
})
TypeScript
// Using $set, $set_once, and $anon_distinct_id
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',
},
})

PostHog.identifyImmediate

identifyImmediate(data): Promise<void>

Send an $identify event immediately and wait for the HTTP send attempt to settle.

Use in short-lived runtimes where the process can freeze before a background flush. Follows the same distinctId matching and $anon_distinct_id rules as identify().

Parameters

ParameterTypeDescription
dataIdentifyMessageThe identify payload containing distinctId and properties

Returns

Promise<void>

Promise that resolves when the identify call settles

Example

TypeScript
// Basic immediate identify
await client.identifyImmediate({
distinctId: 'user_123',
properties: {
name: 'John Doe',
email: 'john@example.com',
},
})

Logs

PostHog.logger

get logger(): Logger

Per-level logger: client.logger.info('message', { attributes }). Equivalent to captureLog at the matching severity.

Example
TypeScript
client.logger.info('checkout completed', { order_id: 'ord_789' })
client.logger.error('payment failed', { code: 'E001' })
Returns

Logger

PostHog.captureLog

captureLog(options): void

Captures one structured log record to PostHog Logs. Attaches the active span's ids and the withContext person and session unless the options set their own.

Parameters

ParameterType
optionsCaptureLogOptions

Returns

void

Example

TypeScript
client.captureLog({ body: 'payment failed', level: 'error', attributes: { code: 'E001' } })

Traces

PostHog.getActiveSpan

getActiveSpan(): Span | null

Experimental

The span currently active on this async execution path, or null outside any withSpan callback.

On the edge build this returns null after an await, because the active span is tracked synchronously there.

Subject to change in a minor release.

Returns

Span | null

Example

TypeScript
// Propagate the trace to another service
const traceparent = posthog.getActiveSpan()?.traceparent()
await fetch(url, { headers: traceparent ? { traceparent } : {} })

PostHog.startSpan

startSpan(name, options?): Span

Experimental

Starts a span without making it active — for work that can't wrap a callback. Prefer withSpan, which ends the span for you.

Always returns a handle, so calling code never has to branch: when the traces option is absent, the SDK is disabled, or the user has opted out, the handle is inert and nothing is exported. An inert handle given a parent header still returns it from traceparent(), so a service with tracing off passes a distributed trace through instead of severing it.

Subject to change in a minor release.

Parameters

ParameterType
namestring
options?StartSpanOptions

Returns

Span

Example

TypeScript
const span = posthog.startSpan('checkout', { attributes: { plan: 'pro' } })
span.setAttribute('cart.items', 3)
span.end()

PostHog.withSpan

withSpan<T>(name, fn): T

Experimental

Runs a callback with a span active for its duration and ends the span for you — at return for a sync callback, at settle for an async one. Takes an optional StartSpanOptions between the name and the callback: withSpan(name, fn) or withSpan(name, options, fn).

Spans started inside the callback nest under it automatically. If the callback throws or rejects, the span records the exception and the original error is rethrown unchanged. A callback that ends the span itself gets the rethrow but not the recording, since the span is already exported by then.

Spans nest across await only on the Node runtime, which tracks the active span with AsyncLocalStorage. The edge build restores the active span when the callback returns its promise, so spans started after an await there begin a new trace.

Subject to change in a minor release.

Type Parameters
Type Parameter
T
Parameters
ParameterType
namestring
fn(span) => T
Returns

T

Example
TypeScript
await posthog.withSpan('POST /checkout', { parent: req.get('traceparent') }, async (span) => {
span.setAttribute('plan', user.plan)
return processOrder()
})

Call Signature

withSpan<T>(name, options, fn): T

Experimental

Runs a callback with a span active for its duration and ends the span for you — at return for a sync callback, at settle for an async one. Takes an optional StartSpanOptions between the name and the callback: withSpan(name, fn) or withSpan(name, options, fn).

Spans started inside the callback nest under it automatically. If the callback throws or rejects, the span records the exception and the original error is rethrown unchanged. A callback that ends the span itself gets the rethrow but not the recording, since the span is already exported by then.

Spans nest across await only on the Node runtime, which tracks the active span with AsyncLocalStorage. The edge build restores the active span when the callback returns its promise, so spans started after an await there begin a new trace.

Subject to change in a minor release.

Type Parameters
Type Parameter
T
Parameters
ParameterType
namestring
optionsStartSpanOptions
fn(span) => T
Returns

T

Example
TypeScript
await posthog.withSpan('POST /checkout', { parent: req.get('traceparent') }, async (span) => {
span.setAttribute('plan', user.plan)
return processOrder()
})

enrichCurrentSpan

enrichCurrentSpan(client): void

Notify installed PostHogContextSpanProcessor instances after request IDs become available.

This helper doesn't load OpenTelemetry, so it's a no-op unless you register PostHogContextSpanProcessor from posthog-node/otel.

Parameters

ParameterType
clientPostHogBackendClient

Returns

void

instrumentRequest

instrumentRequest(posthog, request, handler, options?): Promise<Response>

Experimental

Instruments one request on the fetch API (Request in, Response out): Hono, Bun, Deno, Next route handlers, Cloudflare Workers, and anything else that works that way.

  • reads x-posthog-session-id / x-posthog-distinct-id (or the posthog-js cookie when readPostHogCookie is on) and runs the handler inside withContext, so events and spans carry the person and the replay
  • opens a server span continuing an inbound traceparent, named METHOD route once the route is known
  • marks 5xx responses and thrown errors as span errors (the error is rethrown)
  • records http.server.request.duration (seconds histogram) and http.server.request.count, by method, route and status code, and hands their flush to the waitUntil client option when set

The request context (session and distinct ID on events and spans) needs withContext, which the edge entrypoint (Cloudflare Workers, Vercel Edge) does not support: there the span and metrics are still recorded, but captures inside the handler do not pick up the request's IDs. Pass them explicitly on that runtime.

Subject to change in a minor release.

Parameters

ParameterType
posthogPostHogForRequests
requestRequest
handler() => Response | Promise<Response>
options?InstrumentRequestOptions

Returns

Promise<Response>

Example

TypeScript
export default {
fetch: (request: Request) => instrumentRequest(posthog, request, () => app.fetch(request)),
}

posthogHonoMiddleware

posthogHonoMiddleware(posthog, options?): (c, next) => Promise<void>

Experimental

Hono middleware that instruments every request. See instrumentRequest. The span is named after the matched route (GET /api/users/:id), and a thrown error is recorded as a 500.

Subject to change in a minor release.

Parameters

ParameterType
posthogPostHogForRequests
options?Omit<InstrumentRequestOptions, "getRoute">

Returns

(c, next) => Promise<void>

Example

TypeScript
app.use('*', posthogHonoMiddleware(posthog))

PostHogContextSpanProcessor

OpenTelemetry SpanProcessor that stamps posthogDistinctId and sessionId from the active PostHog context onto recording spans and the nearest enclosing SERVER span.

Requires @opentelemetry/api (^1.2.0) as an optional peer dependency. Skips spans when the client is disabled or opted out.

Example

TypeScript
import { BasicTracerProvider } from '@opentelemetry/sdk-trace-base'
import { PostHog } from 'posthog-node'
import { PostHogContextSpanProcessor } from 'posthog-node/otel'
const posthog = new PostHog('<ph_project_api_key>', { host: 'https://us.i.posthog.com' })
const provider = new BasicTracerProvider({ spanProcessors: [new PostHogContextSpanProcessor(posthog)] })

Constructors

Constructor

new PostHogContextSpanProcessor(posthog): PostHogContextSpanProcessor

Create a span processor bound to one PostHog client instance.

Parameters
ParameterTypeDescription
posthogPostHogBackendClientClient whose active request context populates span attributes
Returns

PostHogContextSpanProcessor

Methods

forceFlush()

forceFlush(): Promise<void>

Returns

Promise<void>

onEnd()

onEnd(): void

Returns

void

onStart()

onStart(span, parentContext?): void

Parameters
ParameterType
spanSpan
parentContext?Context
Returns

void

shutdown()

shutdown(): Promise<void>

Returns

Promise<void>

Alias

PostHog.alias

alias(data): void

Queue a $create_alias event linking alias (the previous or secondary ID) to distinctId (the primary user ID).

distinctId falls back to withContext() when blank, while alias never reads from context or register(). Never alias to shared placeholder values such as 'anonymous' or 'null'. Frontend posthog.identify() already links anonymous users, so backend alias() is mainly for backend-only flows.

Parameters

ParameterTypeDescription
data{ alias: string; disableGeoip?: boolean; distinctId: string; options?: V1EventOptions; }Primary distinctId, previous alias, and optional flags or options
data.aliasstring-
data.disableGeoip?boolean-
data.distinctIdstring-
data.options?V1EventOptions-

Returns

void

Example

TypeScript
// Link an anonymous user ID to a primary user ID
client.alias({
distinctId: 'user_456',
alias: 'anonymous_123',
})

PostHog.aliasImmediate

aliasImmediate(data): Promise<void>

Send a $create_alias event immediately to link alias to distinctId.

Follows the same ID precedence and placeholder warnings as alias(). Use in short-lived runtimes where the process can freeze before a background flush.

Parameters

ParameterTypeDescription
data{ alias: string; disableGeoip?: boolean; distinctId: string; options?: V1EventOptions; }Primary distinctId, previous alias, and optional flags or options
data.aliasstring-
data.disableGeoip?boolean-
data.distinctIdstring-
data.options?V1EventOptions-

Returns

Promise<void>

Promise that resolves when the alias call settles

Example

TypeScript
// Link an anonymous user ID to a primary user ID immediately
await client.aliasImmediate({
distinctId: 'user_456',
alias: 'anonymous_123',
})

Capture AI

PostHog.captureAi

captureAi(props): string | undefined

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. The payload is sent as given, except that an event whose properties exceed the per-event size cap is sent without its content properties.

Parameters

ParameterTypeDescription
propsEventMessageThe event properties

Returns

string | undefined

The event UUID, or undefined when the client is disabled

PostHog.captureAiImmediate

captureAiImmediate(props): Promise<string | undefined>

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

ParameterTypeDescription
propsEventMessageThe event properties

Returns

Promise<string | undefined>

The event UUID, or undefined when the client is disabled

Capture exception

PostHog.captureException

captureException(error, options?): void

Capture an error exception as an event.

Parameters

ParameterTypeDescription
errorunknownThe error to capture
options?CaptureExceptionOptionsOptional distinct id, properties, options, uuid, flags snapshot and level

Returns

void

Remarks

The 5.x positional form captureException(error, distinctId, properties, uuid, flags) still works in 6.x but logs a deprecation error once per process, and will be removed in the next major version.

Examples

TypeScript
// Capture an error with user ID
try {
// Some risky operation
riskyOperation()
} catch (error) {
client.captureException(error, { distinctId: 'user_123' })
}
TypeScript
// Capture with additional properties and a level
try {
apiCall()
} catch (error) {
client.captureException(error, {
distinctId: 'user_123',
properties: { endpoint: '/api/users', method: 'POST', status_code: 500 },
level: 'warning',
})
}

PostHog.captureExceptionImmediate

captureExceptionImmediate(error, options?): Promise<void>

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

Parameters

ParameterTypeDescription
errorunknownThe error to capture
options?CaptureExceptionOptionsOptional distinct id, properties, options, uuid, flags snapshot and level

Returns

Promise<void>

Promise that resolves when the error is captured

Remarks

The 5.x positional form captureExceptionImmediate(error, distinctId, properties, flags) still works in 6.x but logs a deprecation error once per process, and will be removed in the next major version.

Examples

TypeScript
// Capture an error immediately with user ID
try {
// Some risky operation
riskyOperation()
} catch (error) {
await client.captureExceptionImmediate(error, { distinctId: 'user_123' })
}
TypeScript
// Capture with additional properties
try {
apiCall()
} catch (error) {
await client.captureExceptionImmediate(error, {
distinctId: 'user_123',
properties: { endpoint: '/api/users', method: 'POST', status_code: 500 },
})
}

PostHogSentryIntegration

Class-based Sentry integration.

Deprecated

This integration is deprecated and will be removed in a future major version. Use PostHog Error Tracking for Node instead: https://posthog.com/docs/error-tracking/installation/node

Implements

  • _SentryIntegrationClass

Constructors

Constructor

new PostHogSentryIntegration(_posthog, organization?, prefix?, severityAllowList?, sendExceptionsToPostHog?): PostHogSentryIntegration

Parameters
ParameterType
_posthogPostHogBackendClient
organization?string
prefix?string
severityAllowList?("fatal" | "error" | "warning" | "log" | "info" | "debug")[] | "*"
sendExceptionsToPostHog?boolean
Returns

PostHogSentryIntegration

Properties

PropertyModifierTypeDefault value
namepublic readonly"posthog-node"NAME
setupOncepublic(addGlobalEventProcessor, getCurrentHub) => voidundefined
POSTHOG_ID_TAGpublic static readonly"posthog_distinct_id"'posthog_distinct_id'

createReactRouterErrorHandler

createReactRouterErrorHandler<A>(posthog, options?): (error, args) => Promise<void>

Experimental

Returns a React Router handleError that captures server errors (loaders, actions, middleware, resource routes, server rendering) with the request's person, session and request properties. It reports the page URL even for the .data requests of client navigations, never the query string. It skips aborted requests and the 404 and 405 responses the router produces itself, and captures the error inside a data(error, init) a middleware threw. The event is marked unhandled, with the middleware mechanism and $exception_source: 'react_router.handle_error'.

IDs set with withContext (in a middleware, for example) win. Otherwise, linking page loads to the browser's person and session reads the posthog-js cookie, which needs the client's readPostHogCookie: true, and requests with x-posthog-* tracing headers link without it. An anonymous visitor's exceptions carry their anonymous distinct ID and stay personless. When the visitor's consent cookie opts out, the event keeps no person, session, device, user agent or IP.

Errors raised while streaming, after the shell was sent, skip handleError and reach the onError of the React stream in entry.server.tsx; call the same handler there. An error object is captured once per request, however many hooks or handlers see it.

The returned handler resolves once the event is queued. On a serverless host, pass the platform's waitUntil as the client's waitUntil option. On Cloudflare Workers, create the client and the handler per request, with the request's ctx.waitUntil: a client kept across requests in a Workers isolate delivers only the first request's events.

Subject to change in a minor release.

Type Parameters

Type ParameterDefault type
A extends ReactRouterErrorArgsReactRouterErrorArgs

Parameters

ParameterType
posthogPostHogBackendClient
options?ReactRouterErrorHandlerOptions<A>

Returns

(error, args) => Promise<void>

Example

TypeScript
// app/entry.server.tsx
const posthog = new PostHog('<ph_project_token>', { host: 'https://us.i.posthog.com', readPostHogCookie: true })
export const handleError = createReactRouterErrorHandler(posthog)
// In handleRequest, in the renderToPipeableStream options:
onError(error: unknown) {
responseStatusCode = 500
if (shellRendered && !request.signal.aborted) {
void handleError(error, { request })
}
},

sentryIntegration

sentryIntegration(_posthog, options?): _SentryIntegration

Creates the function-based Sentry integration.

Parameters

ParameterType
_posthogPostHogBackendClient
options?SentryIntegrationOptions

Returns

_SentryIntegration

Deprecated

This integration is deprecated and will be removed in a future major version. Use PostHog Error Tracking for Node instead: https://posthog.com/docs/error-tracking/installation/node

setupExpressErrorHandler

setupExpressErrorHandler(_posthog, app): void

Register Express error-handling middleware after your routes to capture unhandled exceptions.

Attaches request context, $response_status_code, and $session_id, skips errors already captured by process autocapture, and forwards each error to next(error).

Parameters

ParameterTypeDescription
_posthogPostHogBackendClientPostHog client instance
app{ use: (middleware) => unknown; }Express app with .use()
app.use(middleware) => unknown-

Returns

void

Debug

PostHog.isDebug

get isDebug(): boolean

Checks whether debug logging is enabled on this client.

Example
TypeScript
if (client.isDebug) {
console.log('PostHog debug logging is active')
}
Returns

boolean

true when debug logging is active

PostHog.debug

debug(enabled?): void

Enable or disable debug logging.

Parameters

ParameterTypeDefault valueDescription
enabled?booleantrueWhether to enable debug logging

Returns

void

Examples

TypeScript
// Enable debug logging
client.debug(true)
TypeScript
// Disable debug logging
client.debug(false)

Emails

PostHog.emails

get emails(): Emails

Send transactional email from PostHog templates or inline code, read send status, and update topic preferences.

  • Credentials and scopes. Needs secretKey (phs_...). send needs transactional_email:write, get needs transactional_email:read or transactional_email:write, setPreferences needs messaging_preference:write, and hog_flow:write keys cover all three. Set enableLocalEvaluation: false when the key is only for email.
  • Routing and retries. Requests go to appHost, or the PostHog Cloud app host for host. Configure emailRequestTimeoutMs and emailRequestMaxRetries per client.
  • Result handling. send, get, and setPreferences resolve to { data, error } and never reject. data.id is the queued email's ID for get.
  • Lifecycle. A disabled client returns client_disabled, and a shut-down client returns client_closed.
Example
TypeScript
const client = new PostHog('phc_...', { secretKey: 'phs_...', host: 'https://eu.i.posthog.com' })
const { data, error } = await client.emails.send({
to: 'user@example.com',
templateKey: 'welcome',
subject: 'Welcome to Acme',
html: '<p>Hi Ada, welcome to Acme.</p>',
distinctId: 'user_123',
idempotencyKey: 'welcome:user_123',
})
if (error) {
console.error(error.code, error.message)
} else {
const status = await client.emails.get(data.id) // later, for example from a job
}
// From a preference center: opt out of one topic, keep the rest
await client.emails.setPreferences({ to: 'user@example.com', topics: { newsletter: false } })
Returns

Emails

Description

The posthog.emails API: sends transactional email from PostHog templates or from content your code rendered, reads send status, and sets topic preferences. Needs secretKey.

EmailError

PostHog refused an email call, or the client could not tell whether it succeeded.

Branch on code, PostHog's stable error code, or on name, a coarse category of the failure. The message never contains the secret key or the request body.

Extends

  • Error

Constructors

Constructor

new EmailError(params): EmailError

Parameters
ParameterType
paramsEmailErrorParams
Returns

EmailError

Properties

PropertyModifierTypeDescriptionOverrides
codereadonlystringPostHog's error code, such as quota_limited, or an SDK code, such as network_error, missing_secret_key, missing_app_host, client_disabled or client_closed.-
docsUrl?readonlystringA docs page about the error, when PostHog sent one.-
field?readonlystringThe request field the error is about, when PostHog named one.-
fix?readonlystringWhat to change before you call again, when PostHog or the client said.-
namepublicEmailErrorNameA coarse category of the failure, such as rate_limit_exceeded.Error.name
retryAfterMs?readonlynumberHow long PostHog asked the client to wait before it sends again, in milliseconds.-
statusCode?readonlynumberThe HTTP status, when PostHog or its file storage answered.-
why?readonlystringWhy PostHog or the client refused the call, when PostHog or the client said.-

EmailErrorName

EmailErrorName = "validation_error" | "missing_api_key" | "invalid_permission" | "not_found" | "concurrent_idempotent_requests" | "invalid_idempotent_request" | "rate_limit_exceeded" | "monthly_quota_exceeded" | "service_unavailable" | "application_error"

A coarse category of the failure, for code that branches on the kind of failure rather than the exact code.

EmailErrorParams

PropertyType
cause?unknown
codestring
docsUrl?string
field?string
fix?string
messagestring
retryAfterMs?number
statusCode?number
why?string

Emails

The posthog.emails API: sends transactional email from PostHog email templates or from content your code rendered, reads the status of each email it sent, and sets a recipient's topic preferences.

Methods

get()

get(id): Promise<GetEmailResponse>

Read the status of an email that send() queued, for 30 days after the send. Needs posthog-node 5.61.0 or later.

Resolves to { data, error } and does not reject. data is an EmailStatus: id, status, createdAt, statusAt and reason. The error code is not_found when no email of this project has the ID, when the email is older than 30 days, or for a few seconds after the send. The client doesn't retry not_found, so right after a send, wait a few seconds and call again before you treat the email as missing. Network errors, rate limits and an unavailable service are retried.

Parameters
ParameterType
idstring
Returns

Promise<GetEmailResponse>

send()

send(options): Promise<SendEmailResponse>

Queue one email, from a transactional email template or from content your code rendered.

Resolves to { data, error } and does not reject. data means PostHog queued the email, not that it was delivered. error is an EmailError: branch on its code.

The client retries a network error, a 429 rate limit (not quota_limited or upload_quota_exceeded), a 409 idempotency_key_in_flight, a 503, and a failed attachment upload with a 429 or 5xx. It retries each request up to the send's maxRetries or the client's emailRequestMaxRetries times (default 2), so a send with attachments can retry more times overall. Every retry of the send carries the same idempotency key. It waits about 1 second, then 2, doubling up to 30 seconds, or longer when the Retry-After header asks. When Retry-After asks for more than 30 seconds, it returns the error at once. Each request times out after emailRequestTimeoutMs (default 15000).

A network_error or a 503 doesn't mean the email failed: PostHog may have queued it. Retry with the same idempotencyKey (pass your own, such as welcome:user_123, so a retry outside this call can reuse it), and don't resend it through another email provider.

Parameters
ParameterType
optionsSendEmailOptions
Returns

Promise<SendEmailResponse>

setPreferences()

setPreferences(options): Promise<SetEmailPreferencesResponse>

Opt one recipient out of topics, or back in, in one request. PostHog saves the whole change at once. The same change twice ends the same, but a retry that lands after a newer change for the same recipient undoes that change. A failed call may still have saved the change. Workflows sends skip a marketing topic the recipient opted out of. Needs posthog-node 5.70.0 or later.

Resolves to { data, error } and does not reject. The error code is unknown_topic when a topic key names no topic of the project, and nothing is saved. A plain not_found means the PostHog instance has no preferences API yet. Network errors, rate limits and an unavailable service are retried.

Parameters
ParameterType
optionsSetEmailPreferencesOptions
Returns

Promise<SetEmailPreferencesResponse>

SendEmailOptions

SendEmailOptions = SendTemplateEmailOptions | SendCodeEmailOptions

Options for posthog.emails.send(): a template made in PostHog (templateId), or content from your code (templateKey, subject, and html, text, or react). to is required for both.

SendTemplateEmailOptions

SendTemplateEmailOptions = SendEmailBase & TemplateEmailForm & Without<CodeEmailFields & object>

SendCodeEmailOptions

SendCodeEmailOptions = SendEmailBase & CodeEmailForm & Without<TemplateEmailForm>

SendEmailBase

What every send takes, whatever its form.

Properties

PropertyTypeDescription
distinctId?stringThe recipient's distinct ID in your product. The email's events go to this person. Without it, they go to a person whose distinct ID is the email address.
idempotencyKey?string1 to 255 visible ASCII characters. A send with a key that PostHog has already accepted queues nothing and returns the first send's result. The same key with other options sends nothing and returns an error with code idempotency_key_reused. Without it, the client makes a UUID that covers its own retries. Pass a key derived from what the email is for, such as welcome:user_123, to cover retries outside this call too. PostHog keeps a key for 7 days after it queues the email, so finish every retry within 7 days.
maxRetries?numberOverrides the client's emailRequestMaxRetries for this send. 0 turns retries off.
tostringOne recipient email address.

TemplateEmailForm

A template made transactional in PostHog, sent by its ID. Needs posthog-node 5.61.0 or later. A template send takes no subject, body, sender, copies, or attachments: the template sets them.

Properties

PropertyTypeDescription
templateData?Record<string, unknown>Values for the template's {{ variables.* }} placeholders. Sent as message_data.
templateIdstringThe UUID of an email template made transactional in PostHog.

CodeEmailForm

CodeEmailForm = CodeEmailFields & ({ html: string; react?: never; text?: string; } | { html?: string; react?: never; text: string; } | { html?: never; react: EmailReactElement; text?: string; })

Email content from your code, named by a key: html, text or both, or a react element the client renders. PostHog sends it as is and never stores it. PostHog derives a missing text from the html. Needs posthog-node 5.62.0 or later, and react needs 5.69.0 or later.

CodeEmailFields

PropertyTypeDescription
attachments?EmailAttachment[]Files sent with the email: at most 10, and at most 40 MB for the whole email after Base64 encoding, about 29 MB of files. The SDK checks both before any request. It uploads each file PostHog doesn't have yet, then sends the email. When an upload fails, it sends nothing. Needs posthog-node 5.72.0 or later.
bcc?string | string[]Bare addresses that get a copy the other recipients never see. Needs posthog-node 5.72.0 or later.
captureEngagement?booleanWhether PostHog captures the email's engagement events (sent, delivered, opened, clicked, bounced) as events of the recipient. Defaults to true. A project whose admin turned engagement capture off captures nothing, whatever the send asks. A template made in PostHog follows the project's setting. Deprecated Use tracking: { engagement: false }. It keeps working, but PostHog refuses a send that sets both captureEngagement and tracking.
category?stringDeprecated Code-sent emails are transactional only. A send that sets category is refused with invalid_form before any request, and no email is sent. Send marketing email through a PostHog workflow.
cc?string | string[]Bare addresses, such as 'finance@example.com', that get a copy. Needs posthog-node 5.72.0 or later.
from?stringA verified sender, such as 'Acme <security@example.com>'. Without it, the project's default sender.
headers?Record<string, string>Email headers that PostHog puts on the email itself, not on the request, such as { 'X-Entity-Ref-ID': 'order-1234' }. The client leaves an empty object out and sends the rest as given. PostHog checks the names and values: - At most 8 headers. Allowed names are In-Reply-To, References, List-Unsubscribe, List-Unsubscribe-Post, List-Id, and any name that starts with X-, except X-PostHog- and X-SES-. - Each value is at most 870 ASCII characters, without line breaks. Only an X- header takes non-ASCII text, up to 200 UTF-8 bytes. - A header that PostHog sets itself keeps PostHog's value. PostHog refuses a header it doesn't take with code invalid_header, and the client refuses a value that isn't an object with the same code. A send with templateId doesn't take headers, and the PostHog test sender refuses them with sandbox_fields_unsupported. A PostHog that doesn't take headers yet refuses them with field_not_accepted. Needs posthog-node 6.4.0 or later.
replyTo?string | string[]One address or a list of addresses that replies go to.
sensitive?booleanMarks the email as sensitive, such as one that carries login links, reset tokens or codes. A sensitive email keeps its links as they are unless tracking turns clicks on, leaves its subject off engagement events, and keeps its content out of PostHog's logs. Without it, a send whose templateKey matches a template saved in PostHog follows that template's setting, and any other send is sensitive. PostHog refuses sensitive: false when the matching template is sensitive. Needs posthog-node 5.71.0 or later.
subjectstringThe subject line.
tags?Record<string, string>Tags that PostHog adds to the email's events, such as { plan: 'pro' }. They come back as $email_tags on the sent, delivered, opened, clicked and bounced events, so you can break them down by properties.$email_tags.plan. The client leaves an empty object out and sends the rest as given. PostHog checks the names and values: - At most 10 tags. - A name is 1 to 64 letters, digits, _ and -, and starts with a letter or digit. - A value is 1 to 256 of the same characters. PostHog refuses a tag it doesn't take with code invalid_tag, and the client refuses a value that isn't an object with the same code. A send with templateId doesn't take tags, and the PostHog test sender refuses them with sandbox_fields_unsupported. A PostHog that doesn't take tags yet refuses them with field_not_accepted. Needs posthog-node 6.4.0 or later.
templateKeystringNames the email, such as 'password-reset', so its metrics, logs and status group under it in PostHog. Letters, digits, hyphens and underscores, at most 400.
tracking?boolean | EmailTrackingWhat PostHog tracks for this email. Without it, PostHog counts opens with its open pixel, captures engagement events, and counts clicks only when the email isn't sensitive. - true turns on opens, clicks and engagement events. - false turns off all tracking, including kinds PostHog adds later. PostHog can't count the email's opens or clicks, and captures no engagement events. - An object turns each kind on or off. A key you leave out keeps its default. Turn clicks on for a sensitive email only when its links are safe to send through PostHog's click tracking. Needs posthog-node 5.71.0 or later.

EmailAttachment

A file sent with the email.

Properties

PropertyTypeDescription
contentstring | Uint8Array<ArrayBufferLike>The file's bytes, or its content already Base64 encoded. At least one byte.
contentId?stringShows the file inline where the HTML has <img src="cid:..."> with this id.
contentType?stringA MIME type, such as 'application/pdf'.
filenamestringThe name the recipient sees, such as 'invoice.pdf'.
path?undefinedPostHog can't fetch a file from a path or URL: read the file and pass its content.

EmailTracking

Which kinds of tracking a send with templateKey turns on.

Properties

PropertyTypeDescription
clicks?booleanCounts clicks by sending the email's links through PostHog's click tracking. Defaults to false for a sensitive email and true for any other. Needs opens: PostHog refuses a send with opens: false and clicks: true.
engagement?booleanCaptures the email's engagement events (sent, delivered, opened, clicked, bounced) as events of the recipient. Defaults to true. A project whose admin turned engagement capture off captures nothing, whatever the send asks.
opens?booleanCounts opens with PostHog's open pixel. Defaults to true.

EmailReactElement

A React element, such as <WelcomeEmail firstName="Ada" />. Typed by its shape, so posthog-node needs no React types.

Properties

PropertyType
propsunknown
typeunknown

SendEmailResponse

SendEmailResponse = { data: SendEmailResult; error: null; } | { data: null; error: EmailError; }

What posthog.emails.send() resolves to. Exactly one of data and error is set. The promise does not reject.

SendEmailResult

The queued email. A result means PostHog queued the email, not that it was delivered.

Properties

PropertyTypeDescription
idstringThe queued email's message ID.
replayedbooleanTrue when PostHog had already accepted this idempotency key and returned the first send's result.
warningsEmailWarning[]-

EmailWarning

A warning PostHog returned with a queued email.

Properties

PropertyType
codestring
fix?string
messagestring

GetEmailResponse

GetEmailResponse = { data: EmailStatus; error: null; } | { data: null; error: EmailError; }

What posthog.emails.get() resolves to. Exactly one of data and error is set. The promise does not reject.

EmailStatus

The status of an email that posthog.emails.send() queued.

Properties

PropertyTypeDescription
createdAtstringWhen PostHog queued the email, as an ISO 8601 timestamp.
idstringThe message ID that send() returned.
reasonstring | nullWhy a failed email was not sent, such as provider_error or recipient_suppressed, or the bounce type of a bounced email: hard, soft or unknown. Null otherwise.
statusEmailDeliveryStatus | string & objectWhere the email is now, such as delivered. See EmailDeliveryStatus.
statusAtstringWhen the email reached its current status, as an ISO 8601 timestamp.

EmailDeliveryStatus

EmailDeliveryStatus = "queued" | "sent" | "failed" | "delivered" | "bounced" | "complained"

What happened to an email. Later SDK versions can see values this list does not have yet.

  • queued: the email waits to go out.
  • sent: PostHog handed the email to the email provider.
  • failed: the email was not sent, and reason says why.
  • delivered: the recipient's mail server accepted the email.
  • bounced and complained: the recipient's mail provider reported them after delivery.

SetEmailPreferencesOptions

Options for posthog.emails.setPreferences(). Set allMarketing, topics, or both.

Properties

PropertyTypeDescription
allMarketing?booleanfalse opts the recipient out of every marketing topic. true lifts that opt-out. Applied before topics.
tostringThe recipient's email address, exactly as Workflows sends to it. Matching is exact, so Jane@example.com and jane@example.com are two recipients.
topics?Record<string, boolean>Topic key to false to opt the recipient out of that topic, or true to opt them back in. Topic keys are the ones you set under Workflows opt-outs. Opting back in to one marketing topic after an all-marketing opt-out lifts that opt-out, so allMarketing becomes true, and keeps the other marketing topics opted out. Topics you leave out keep their current choice.

SetEmailPreferencesResponse

SetEmailPreferencesResponse = { data: EmailPreferences; error: null; } | { data: null; error: EmailError; }

What posthog.emails.setPreferences() resolves to. Exactly one of data and error is set. The promise does not reject.

EmailPreferences

A recipient's preferences after the change.

Properties

PropertyTypeDescription
allMarketingboolean | nullfalse when the recipient opted out of all marketing, true when they opted back in, null when they never chose.
tostring-
topicsRecord<string, boolean>Topic key to false (opted out) or true (opted in), for every topic the recipient chose.

Flush

PostHog.flush

flush(): Promise<void>

Sends all queued events and spans, and resolves when every send has finished. It does not reject when delivery fails: those failures arrive on the 'error' event.

It has no overall timeout. In an AWS Lambda handler, race it against the time the invocation has left, and keep 100 ms to return. The race limits the wait. It does not cancel the flush.

Returns

Promise<void>

Example

TypeScript
const remainingMs = Math.max(0, context.getRemainingTimeInMillis() - 100)
let timer: ReturnType<typeof setTimeout> | undefined
try {
await Promise.race([
client.flush(),
new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error('PostHog flush timed out')), remainingMs)
}),
])
} catch (err) {
console.error('PostHog flush failed', err)
} finally {
clearTimeout(timer)
}

Get feature flag

PostHog.getFeatureFlag

getFeatureFlag(key, distinctId, options?): Promise<FeatureFlagValue | undefined>

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

ParameterTypeDescription
keystringThe feature flag key
distinctIdstringThe user's distinct ID
options?{ disableGeoip?: boolean; groupProperties?: Record<string, Properties>; groupPropertyKeysKnownAbsent?: Record<string, string[]>; groups?: Record<string, string>; onlyEvaluateLocally?: boolean; personProperties?: Properties; personPropertyKeysKnownAbsent?: string[]; sendFeatureFlagEvents?: boolean; }Optional configuration for flag evaluation
options.disableGeoip?boolean-
options.groupProperties?Record<string, Properties>-
options.groupPropertyKeysKnownAbsent?Record<string, string[]>-
options.groups?Record<string, string>-
options.onlyEvaluateLocally?boolean-
options.personProperties?Properties-
options.personPropertyKeysKnownAbsent?string[]-
options.sendFeatureFlagEvents?boolean-

Returns

Promise<FeatureFlagValue | undefined>

Promise that resolves to the flag value, or undefined when no evaluation is available

Examples

TypeScript
// 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
}
TypeScript
// With groups and properties
const flagValue = await client.getFeatureFlag('org-feature', 'user_123', {
groups: { organization: 'acme-corp' },
personProperties: { plan: 'enterprise' },
groupProperties: { organization: { tier: 'premium' } }
})
TypeScript
// Only evaluate locally
const flagValue = await client.getFeatureFlag('local-flag', 'user_123', {
onlyEvaluateLocally: true
})

Deprecated

Use evaluateFlags and call flags.getFlag(key) on the returned snapshot. This consolidates flag evaluation into a single /flags request per incoming request and avoids drift between the values your code branched on and the values attached to events. Will be removed in the next major version.

Get feature flag payload

PostHog.getFeatureFlagPayload

getFeatureFlagPayload(key, distinctId, matchValue?, options?): Promise<JsonType | undefined>

Get the payload for a feature flag.

Parameters

ParameterTypeDescription
keystringThe feature flag key
distinctIdstringThe user's distinct ID
matchValue?FeatureFlagValueOptional match value to get payload for
options?{ disableGeoip?: boolean; groupProperties?: Record<string, Properties>; groupPropertyKeysKnownAbsent?: Record<string, string[]>; groups?: Record<string, string>; onlyEvaluateLocally?: boolean; personProperties?: Properties; personPropertyKeysKnownAbsent?: string[]; sendFeatureFlagEvents?: boolean; }Optional configuration for flag evaluation
options.disableGeoip?boolean-
options.groupProperties?Record<string, Properties>-
options.groupPropertyKeysKnownAbsent?Record<string, string[]>-
options.groups?Record<string, string>-
options.onlyEvaluateLocally?boolean-
options.personProperties?Properties-
options.personPropertyKeysKnownAbsent?string[]-
options.sendFeatureFlagEvents?booleanDeprecated THIS OPTION HAS NO EFFECT, kept here for backwards compatibility reasons.

Returns

Promise<JsonType | undefined>

Promise that resolves to the flag payload or undefined

Examples

TypeScript
// Get payload for a feature flag
const payload = await client.getFeatureFlagPayload('flag-key', 'user_123')
if (payload) {
console.log('Flag payload:', payload)
}
TypeScript
// Get payload with specific match value
const payload = await client.getFeatureFlagPayload('flag-key', 'user_123', 'variant-a')
TypeScript
// With groups and properties
const payload = await client.getFeatureFlagPayload('org-flag', 'user_123', undefined, {
groups: { organization: 'acme-corp' },
personProperties: { plan: 'enterprise' }
})

Deprecated

Use evaluateFlags and call flags.getFlagPayload(key) on the returned snapshot. This consolidates flag evaluation into a single /flags request per incoming request. Will be removed in the next major version.

Get feature flag result

PostHog.getFeatureFlagResult

getFeatureFlagResult(key, options?): Promise<FeatureFlagResult | undefined>

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
ParameterTypeDescription
keystringThe feature flag key
options?FlagEvaluationOptionsOptional configuration for flag evaluation
Returns

Promise<FeatureFlagResult | undefined>

Promise that resolves to the flag result or undefined

Examples
TypeScript
// 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)
}
TypeScript
// With groups and properties
const result = await client.getFeatureFlagResult('org-feature', 'user_123', {
groups: { organization: 'acme-corp' },
personProperties: { plan: 'enterprise' }
})

Call Signature

getFeatureFlagResult(key, distinctId, options?): Promise<FeatureFlagResult | undefined>

Parameters
ParameterTypeDescription
keystringThe feature flag key
distinctIdstringThe user's distinct ID
options?FlagEvaluationOptionsOptional configuration for flag evaluation
Returns

Promise<FeatureFlagResult | undefined>

Promise that resolves to the flag result or undefined

Description

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.

Example
TypeScript
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)
}

Get feature flags

PostHog.getAllFlags

getAllFlags(options?): Promise<Record<string, FeatureFlagValue>>

Get all feature flag values for a specific user.

Parameters
ParameterTypeDescription
options?AllFlagsOptionsOptional configuration for flag evaluation
Returns

Promise<Record<string, FeatureFlagValue>>

Promise that resolves to a record of flag keys and their values

Examples
TypeScript
// 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' }
TypeScript
// With specific flag keys
const specificFlags = await client.getAllFlags('user_123', {
flagKeys: ['flag-1', 'flag-2']
})
TypeScript
// With groups and properties
const orgFlags = await client.getAllFlags('user_123', {
groups: { organization: 'acme-corp' },
personProperties: { plan: 'enterprise' }
})

Call Signature

getAllFlags(distinctId, options?): Promise<Record<string, FeatureFlagValue>>

Parameters
ParameterTypeDescription
distinctIdstringThe user's distinct ID
options?AllFlagsOptionsOptional configuration for flag evaluation
Returns

Promise<Record<string, FeatureFlagValue>>

Promise that resolves to a record of flag keys and their values

Description

Get all feature flag values for a specific user.

Get feature flags and payloads

PostHog.getAllFlagsAndPayloads

getAllFlagsAndPayloads(options?): Promise<Partial<Pick<PostHogFlagsResponse, "featureFlags" | "featureFlagPayloads">>>

Get all feature flag values and payloads for a specific user.

Parameters
ParameterTypeDescription
options?AllFlagsOptionsOptional configuration for flag evaluation
Returns

Promise<Partial<Pick<PostHogFlagsResponse, "featureFlags" | "featureFlagPayloads">>>

Promise that resolves to flags and payloads

Examples
TypeScript
// 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)
TypeScript
// With specific flag keys
const result = await client.getAllFlagsAndPayloads('user_123', {
flagKeys: ['flag-1', 'flag-2']
})
TypeScript
// Only evaluate locally
const result = await client.getAllFlagsAndPayloads('user_123', {
onlyEvaluateLocally: true
})

Call Signature

getAllFlagsAndPayloads(distinctId, options?): Promise<Partial<Pick<PostHogFlagsResponse, "featureFlags" | "featureFlagPayloads">>>

Parameters
ParameterTypeDescription
distinctIdstringThe user's distinct ID
options?AllFlagsOptionsOptional configuration for flag evaluation
Returns

Promise<Partial<Pick<PostHogFlagsResponse, "featureFlags" | "featureFlagPayloads">>>

Promise that resolves to flags and payloads

Description

Get all feature flag values and payloads for a specific user.

Evaluate flags

PostHog.evaluateFlags

evaluateFlags(options?): Promise<FeatureFlagEvaluations>

Evaluate all feature flags for a user in a single call and return a FeatureFlagEvaluations 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.

Exposure events. isEnabled() and getFlag() send a $feature_flag_called event the first time each flag value is read for a user. Experiments use these events as exposures. When a config version 2 flag assigns an experiment variant, locally or remotely, the read also sends $experiment_exposure, once per user, groups, flag, rule and variant. The client's sendFeatureFlagEvent option sets the default for these reads. Pass { sendFeatureFlagEvents: true } or { sendFeatureFlagEvents: false } to a read to override it, so one snapshot can serve both experiment flags and flags that should send no events. The option governs both events. getFlagPayload() never sends events.

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
ParameterTypeDescription
options?AllFlagsOptionsOptional 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; the snapshot's unresolvedFlags lists them with a reason.
Returns

Promise<FeatureFlagEvaluations>

Promise that resolves to a FeatureFlagEvaluations snapshot

Examples

Basic usage:

TypeScript
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 /flags request to specific keys:

TypeScript
const flags = await client.evaluateFlags('user_123', {
flagKeys: ['new-dashboard', 'checkout-flow'],
personProperties: { plan: 'enterprise' },
})

Attach only the flags the developer actually checked:

TypeScript
const flags = await client.evaluateFlags('user_123')
if (flags.isEnabled('new-dashboard')) { ... }
client.capture({ distinctId: 'user_123', event: 'page_viewed', flags: flags.onlyAccessed() })

Use withContext() to avoid repeating the distinctId:

TypeScript
await client.withContext({ distinctId: 'user_123' }, async () => {
const flags = await client.evaluateFlags()
if (flags.isEnabled('new-dashboard')) { ... }
client.capture({ event: 'page_viewed', flags })
})

Call Signature

evaluateFlags(distinctId, options?): Promise<FeatureFlagEvaluations>

Parameters
ParameterTypeDescription
distinctIdstringThe user's distinct ID
options?AllFlagsOptionsOptional configuration for flag evaluation. flagKeys scopes local evaluation, the /flags request, and the returned snapshot. Missing local keys trigger fallback unless onlyEvaluateLocally is true.
Returns

Promise<FeatureFlagEvaluations>

Description

Evaluate all feature flags for a specific user.

FeatureFlagEvaluations

A snapshot of feature flag evaluations for a single distinctId at a point in time.

Returned by IPostHog.evaluateFlags — branch on isEnabled() / getFlag() and pass the same object to capture() via the flags option so the captured event carries the exact flag values the code branched on.

TypeScript
const flags = await posthog.evaluateFlags(distinctId, { personProperties: { plan: 'enterprise' } })
if (flags.isEnabled('new-dashboard')) {
renderNewDashboard()
}
posthog.capture({ distinctId, event: 'page_viewed', flags })

To narrow the set of flags that get attached to a captured event, use the in-memory helpers only([...]) and onlyAccessed(). To narrow the set of flags requested from the server in the first place, pass flagKeys to evaluateFlags().

Accessors

keys
Get Signature

get keys(): string[]

Returns the flag keys that are part of this evaluation.

Returns

string[]

unresolvedFlags
Get Signature

get unresolvedFlags(): Readonly<Record<string, UnresolvedFlagReason>>

Flags that have a loaded local definition but that neither local evaluation nor a remote fallback resolved, mapped to the reason local evaluation was inconclusive. These flags are absent from keys, and their accessors return undefined (isEnabled returns false). Reading this does not count as an access and does not fire any event.

Always empty on snapshots returned by only() / onlyAccessed().

Returns

Readonly<Record<string, UnresolvedFlagReason>>

Methods

getFlag()

getFlag(key, options?): FeatureFlagValue | undefined

Get the evaluated value of a feature flag. Fires a $feature_flag_called event on the first access per (distinctId, flag, value) tuple, unless events are off for this read (see options.sendFeatureFlagEvents).

Returns the variant string for multivariate flags, true for boolean flags that evaluate on, false for boolean flags that conclusively evaluate off, and undefined for flags that were not returned by the evaluation. Cached inactive definitions are conclusive false results during local evaluation, while remote evaluation omits globally inactive flags.

Parameters
ParameterTypeDescription
keystringThe feature flag key
options?{ sendFeatureFlagEvents?: boolean; }sendFeatureFlagEvents: whether this read sends a $feature_flag_called event. Defaults to the client's sendFeatureFlagEvent option, which defaults to true. When false, the read sends nothing and does not mark the flag as reported, so a later read that sends events still reports it. The flag still counts as accessed for onlyAccessed().
options.sendFeatureFlagEvents?boolean-
Returns

FeatureFlagValue | undefined

getFlagPayload()

getFlagPayload(key): JsonType | undefined

Get the payload associated with a feature flag. Does not count as an access for onlyAccessed() and does not fire any event.

Parameters
ParameterType
keystring
Returns

JsonType | undefined

isEnabled()

isEnabled(key, options?): boolean

Check whether a feature flag is enabled. Fires a $feature_flag_called event on the first access per (distinctId, flag, value) tuple, deduped via the SDK's existing cache, unless events are off for this read (see options.sendFeatureFlagEvents).

Flags that were not returned from the underlying evaluation resolve to options.defaultValue (false unless overridden). A flag that has a value — including a conclusive false result and variant strings — always wins over options.defaultValue. Use getFlag() to distinguish an absent result from false.

Parameters
ParameterTypeDescription
keystringThe feature flag key
options?{ defaultValue?: boolean; sendFeatureFlagEvents?: boolean; }defaultValue: the result when the flag is not in the snapshot. sendFeatureFlagEvents: whether this read sends a $feature_flag_called event. Defaults to the client's sendFeatureFlagEvent option, which defaults to true. When false, the read sends nothing and does not mark the flag as reported, so a later read that sends events still reports it. The flag still counts as accessed for onlyAccessed().
options.defaultValue?boolean-
options.sendFeatureFlagEvents?boolean-
Returns

boolean

only()

only(keys): FeatureFlagEvaluations

Return a filtered copy containing only flags with the given keys. Keys that are not present in the evaluation are dropped and logged as a warning.

Note: like onlyAccessed(), the returned snapshot is intended for capture(). Branching on a filtered key that was excluded from the slice is a no-op.

Parameters
ParameterType
keysstring[]
Returns

FeatureFlagEvaluations

onlyAccessed()

onlyAccessed(): FeatureFlagEvaluations

Return a filtered copy containing only flags that have been accessed via isEnabled() or getFlag() before this call, including reads that sent no $feature_flag_called event.

Order-dependent: if nothing has been accessed yet, the returned snapshot is empty. The method honors its name — pre-access if you want a populated result.

Note: the returned snapshot is intended for capture(), not for further branching. Calling isEnabled() / getFlag() on it for a key that was filtered out is a no-op (no event is fired) — the flag wasn't actually missing, it was excluded from the slice.

Returns

FeatureFlagEvaluations

Group identify

PostHog.groupIdentify

groupIdentify(data): void

Queue a $groupidentify event to create or update a group and its properties (requires Group Analytics).

Projects support up to 5 group types. Set name in properties for the group's display name in PostHog, otherwise PostHog shows groupKey. When distinctId is omitted outside withContext(), it falls back to $<groupType>_<groupKey>. Group identify events don't inherit context sessionId. Pass groups on capture() and evaluateFlags() to link events and flags to the group.

Parameters

ParameterTypeDescription
dataGroupIdentifyMessageGroup identify payload

Returns

void

Examples

TypeScript
// Create or update a company group
client.groupIdentify({
groupType: 'company',
groupKey: 'acme-corp',
properties: {
name: 'Acme Corporation',
industry: 'Technology',
employee_count: 500,
},
distinctId: 'user_123',
})
TypeScript
// Update organization properties using fallback distinctId ($organization_org-456)
client.groupIdentify({
groupType: 'organization',
groupKey: 'org-456',
properties: {
plan: 'enterprise',
region: 'US-West',
},
})

PostHog.groupIdentifyImmediate

groupIdentifyImmediate(data): Promise<void>

Send a $groupidentify event immediately and wait for the HTTP send attempt to settle.

Follows the same name property, distinctId fallback ($<groupType>_<groupKey>), and groups linking rules as groupIdentify(). Use in short-lived runtimes where the process can freeze before a background flush.

Parameters

ParameterTypeDescription
dataGroupIdentifyMessageGroup identify payload

Returns

Promise<void>

Promise that resolves when the group identify call settles

Example

TypeScript
// Immediately create or update a company group
await client.groupIdentifyImmediate({
groupType: 'company',
groupKey: 'acme-corp',
properties: {
name: 'Acme Corporation',
industry: 'Technology',
employee_count: 500,
},
})

Is feature enabled

PostHog.isFeatureEnabled

isFeatureEnabled(key, distinctId, options?): Promise<boolean | undefined>

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

Parameters

ParameterTypeDescription
keystringThe feature flag key
distinctIdstringThe user's distinct ID
options?{ disableGeoip?: boolean; groupProperties?: Record<string, Properties>; groupPropertyKeysKnownAbsent?: Record<string, string[]>; groups?: Record<string, string>; onlyEvaluateLocally?: boolean; personProperties?: Properties; personPropertyKeysKnownAbsent?: string[]; sendFeatureFlagEvents?: boolean; }Optional configuration for flag evaluation
options.disableGeoip?boolean-
options.groupProperties?Record<string, Properties>-
options.groupPropertyKeysKnownAbsent?Record<string, string[]>-
options.groups?Record<string, string>-
options.onlyEvaluateLocally?boolean-
options.personProperties?Properties-
options.personPropertyKeysKnownAbsent?string[]-
options.sendFeatureFlagEvents?boolean-

Returns

Promise<boolean | undefined>

Promise that resolves to true if the flag evaluates on, false if it conclusively evaluates off, or undefined when no evaluation is available

Examples

TypeScript
// 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')
}
TypeScript
// With groups and properties
const isEnabled = await client.isFeatureEnabled('org-feature', 'user_123', {
groups: { organization: 'acme-corp' },
personProperties: { plan: 'enterprise' }
})

Deprecated

Use evaluateFlags and call flags.isEnabled(key) on the returned snapshot. This consolidates flag evaluation into a single /flags request per incoming request. Will be removed in the next major version.

Is opt out

PostHog.isDisabled

get isDisabled(): boolean

Checks whether the client is disabled from capturing events.

Example
TypeScript
if (!client.isDisabled) {
client.capture({ distinctId: 'user_123', event: 'page_viewed' })
}
Returns

boolean

true when capture and network requests are disabled

PostHog.optedOut

get optedOut(): boolean

Checks whether the client is currently opted out.

Example
TypeScript
if (client.optedOut) {
console.log('Capture is paused for this client')
}
Returns

boolean

true when the client is opted out

Opt in

PostHog.disable

disable(): Promise<void>

Disable the PostHog client (opt-out).

Returns

Promise<void>

Promise that resolves when the client is disabled

Example

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

PostHog.enable

enable(): Promise<void>

Enable the PostHog client (opt-in).

Returns

Promise<void>

Promise that resolves when the client is enabled

Example

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

PostHog.optIn

optIn(): Promise<void>

Opts the client in so it resumes capturing events.

Equivalent to enable().

Returns

Promise<void>

Promise that resolves when the client opts back in

Example

TypeScript
await client.optIn()

PostHog.optOut

optOut(): Promise<void>

Opts the client out so it stops capturing events.

Equivalent to disable().

Returns

Promise<void>

Promise that resolves when the client opts out

Example

TypeScript
await client.optOut()

Register

PostHog.register

register(properties): Promise<void>

Register properties that every event sent by this client carries.

Parameters

ParameterTypeDescription
propertiesPostHogEventPropertiesThe properties to add to every event

Returns

Promise<void>

Remarks

Each event fills the keys it left unset in this order: the event's own values, then context properties, then these, then the values the SDK adds (such as $is_server and $geoip_disable). beforeSend sees the result and can change it.

A $process_person_profile registered here never reaches $identify, $create_alias, $merge_dangerously, $groupidentify, $set or $set_once events (see registerOptions()).

Example

TypeScript
await client.register({ service: 'billing' })

Reload feature flags

PostHog.reloadFeatureFlags

reloadFeatureFlags(): Promise<void>

Reload feature flag definitions from the configured cache provider or PostHog for local evaluation.

Returns

Promise<void>

Promise that resolves when flags are reloaded

Examples

TypeScript
// Force reload of feature flags
await client.reloadFeatureFlags()
console.log('Feature flags reloaded')
TypeScript
// Reload before evaluating flags
await client.reloadFeatureFlags()
const flags = await client.evaluateFlags('user_123')
const value = flags.getFlag('flag-key')

Set person properties

PostHog.setPersonProperties

setPersonProperties(data): void

Queue a $set event to set or set-once properties on a person profile.

Falls back to withContext() when distinctId is blank, and no-ops when both properties and propertiesOnce are empty.

Parameters

ParameterTypeDescription
dataSetPersonPropertiesMessageDistinct ID and person properties to set

Returns

void

Example

TypeScript
client.setPersonProperties({
distinctId: 'user_123',
properties: { plan: 'premium' },
propertiesOnce: { first_seen: '2026-06-15' },
})

PostHog.unsetPersonProperties

unsetPersonProperties(data): void

Queue a $set event carrying $unset to remove properties from a person profile.

Falls back to withContext() when distinctId is blank, and no-ops when properties is empty.

Parameters

ParameterTypeDescription
dataUnsetPersonPropertiesMessageDistinct ID and property names to unset

Returns

void

Example

TypeScript
client.unsetPersonProperties({
distinctId: 'user_123',
properties: ['plan', 'email'],
})

Shutdown

PostHog.shutdown

shutdown(shutdownTimeoutMs?): Promise<void>

Shuts down the client, drains pending queues, and flushes queued telemetry before exit.

Call shutdown() once on process exit. Use flush() when you'll keep reusing the client.

  • What it stops and drains. Halts flag polling, calls flagDefinitionCacheProvider.shutdown(), and drains analytics events, AI events, logs, metrics, and ended spans.
  • Shared timeout budget. Analytics queues and OTel signal flushing share shutdownTimeoutMs. Open spans that haven't ended are discarded.
  • Delivery vs. ingestion. Resolving confirms the client tried to drain within shutdownTimeoutMs, not that PostHog ingested every event.

Parameters

ParameterTypeDefault valueDescription
shutdownTimeoutMs?number30000Maximum wait in milliseconds, defaulting to 30000

Returns

Promise<void>

Promise that resolves when shutdown finishes or hits shutdownTimeoutMs

Examples

TypeScript
await client.shutdown()
TypeScript
// Shutdown with a 5-second timeout
await client.shutdown(5000)

Unregister

PostHog.unregister

unregister(property): Promise<void>

Remove a property added with register().

Parameters

ParameterTypeDescription
propertystringThe property name to remove

Returns

Promise<void>

Flag definition loader

PostHog.isLocalEvaluationReady

isLocalEvaluationReady(): boolean

Check if local evaluation of feature flags is ready.

Returns

boolean

true if flag definitions have loaded and include at least one flag, false otherwise

Example

TypeScript
// Check if ready before evaluating
if (client.isLocalEvaluationReady()) {
const flags = await client.evaluateFlags('user_123', { onlyEvaluateLocally: true })
const value = flags.getFlag('flag-key')
} else {
const flags = await client.evaluateFlags('user_123')
const value = flags.getFlag('flag-key')
}

Remarks

Readiness requires at least one loaded flag definition. A successful load that returns no flags (for example, after every flag is deleted) doesn't count as ready, and readiness returns to false if a later load returns no flags. To react to every successful load, including empty ones, listen for the localEvaluationFlagsLoaded event, which reports the number of loaded flags.

PostHog.waitForLocalEvaluationReady

waitForLocalEvaluationReady(timeoutMs?): Promise<boolean>

Wait for local evaluation of feature flags to be ready.

Parameters

ParameterTypeDefault valueDescription
timeoutMs?number30000Timeout in milliseconds

Returns

Promise<boolean>

Promise that resolves to true if ready, false if timed out or if the next load returned no flags

Examples

TypeScript
// Wait for local evaluation
const isReady = await client.waitForLocalEvaluationReady()
if (isReady) {
console.log('Local evaluation is ready')
} else {
console.log('Local evaluation timed out')
}
TypeScript
// Wait with custom timeout
const isReady = await client.waitForLocalEvaluationReady(10000) // 10 seconds

Remarks

Like isLocalEvaluationReady, this requires at least one loaded flag definition. If the first load after the call returns no flags, the promise resolves to false without waiting for the timeout. To react to every successful load, including empty ones, listen for the localEvaluationFlagsLoaded event, which reports the number of loaded flags.

Remote config

PostHog.getRemoteConfigPayload

getRemoteConfigPayload(flagKey): Promise<JsonType | undefined>

Get the remote config payload for a feature flag.

Parameters

ParameterTypeDescription
flagKeystringThe feature flag key

Returns

Promise<JsonType | undefined>

Promise that resolves to:

  • the payload, when the flag has one
  • null, when the flag is disabled
  • undefined, when the flag has no payload, or the request failed. A response with a status outside 200 to 299 emits a RemoteConfigPayloadError carrying the statusCode and flagKey on the client's error event; a network error, a timeout or an unreadable body emits the underlying error there.

Example

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

Throws

Error if neither secretKey nor personalApiKey is configured. Set enableLocalEvaluation: false when secretKey is only for remote config or email.

RemoteConfigPayloadError

PostHog answered a getRemoteConfigPayload request with a status outside 200 to 299.

Emitted on the client's error event; the call itself resolves to undefined. Branch on statusCode, for example 404 when the flag does not exist or is not a remote config flag, versus 429 or 5xx when the request should be tried again later.

Extends

  • Error

Constructors

Constructor

new RemoteConfigPayloadError(flagKey, statusCode): RemoteConfigPayloadError

Parameters
ParameterTypeDescription
flagKeystringThe key of the flag whose payload was requested.
statusCodenumberThe HTTP status PostHog answered with.
Returns

RemoteConfigPayloadError

Properties

PropertyModifierTypeDefault valueDescriptionOverrides
flagKeyreadonlystringundefinedThe key of the flag whose payload was requested.-
namepublicstring'RemoteConfigPayloadError'-Error.name
statusCodereadonlynumberundefinedThe HTTP status PostHog answered with.-

SDK utils

PostHog.metrics

get metrics(): Metrics

The posthog.metrics API: a statsd-style pre-aggregating metrics client — alpha. Samples are folded into per-series aggregates in memory and flushed periodically as one OTLP data point per series per window, so recording from hot paths is cheap. Configure via the metrics client option.

Example
TypeScript
client.metrics.count('jobs.processed', 1, { attributes: { queue: 'default' } })
client.metrics.gauge('queue.depth', 42)
client.metrics.histogram('job.duration', 187, { unit: 'ms' })
Returns

Metrics

Description

The posthog.metrics API: a statsd-style pre-aggregating metrics client (count, gauge, histogram) — alpha. Samples are folded into per-series aggregates in memory and flushed periodically. Configure via the metrics client option.

PostHog.getContext

getContext(): ContextData | undefined

Read the active withContext() data, or undefined outside a context (and always undefined on posthog-node/edge).

Returns

ContextData | undefined

The current context data, or undefined if no context is active

Example

TypeScript
// Get current context within a withContext block
posthog.withContext({ distinctId: 'user_123' }, () => {
const context = posthog.getContext()
console.log(context?.distinctId) // 'user_123'
})

PostHog.getFeatureFlagEvaluationRuntime

getFeatureFlagEvaluationRuntime(key): FeatureFlagEvaluationRuntime | undefined

Get where a locally loaded feature flag is meant to be evaluated.

Parameters

ParameterTypeDescription
keystringThe feature flag key

Returns

FeatureFlagEvaluationRuntime | undefined

The flag's evaluation runtime, or undefined when local evaluation has not loaded a definition for this key

Remarks

Read from the definitions local evaluation already holds, so no request is made. A definition that carries no runtime reports all, the default PostHog applies.

Example

TypeScript
const runtime = client.getFeatureFlagEvaluationRuntime('my-flag')
// Returns: 'client'

PostHog.getFeatureFlagKeysByEvaluationRuntime

getFeatureFlagKeysByEvaluationRuntime(evaluationRuntime): string[]

Get the keys of locally loaded flags that a runtime can evaluate.

Parameters

ParameterTypeDescription
evaluationRuntimeFeatureFlagEvaluationRuntimeThe runtime to match

Returns

string[]

The matching flag keys, in the order local evaluation loaded them. Empty when no definitions are loaded

Remarks

A flag set to all suits either runtime, so it is returned for client and for server, and asking for all returns every loaded flag. Use this to decide which flags to hand to a browser when a backend serves flags to its own frontend.

Example

TypeScript
const clientKeys = client.getFeatureFlagKeysByEvaluationRuntime('client')
// Returns: ['web-banner', 'shared-copy']

PostHog.on

on(event, cb): () => void

Listens for an SDK event and returns a function that removes the listener. The SDK does not throw for failures in background work, so listen for them on the 'error' event.

Parameters

ParameterType
eventstring
cb(...args) => void

Returns

() => void

Example

JavaScript
posthog.on('error', (err) => {
console.error('PostHog had an error', err)
})

PostHog.overrideFeatureFlags

overrideFeatureFlags(overrides): void

Override feature flags locally. Useful for testing and local development. Overridden flags take precedence over both local evaluation and remote evaluation.

Parameters

ParameterTypeDescription
overridesOverrideFeatureFlagsOptionsFlag overrides configuration

Returns

void

Example

TypeScript
// 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 } }
})

PostHog.registerOptions

registerOptions(options): Promise<void>

Register options that every event sent by this client carries.

Parameters

ParameterTypeDescription
optionsV1EventOptionsThe options to add to every event

Returns

Promise<void>

Remarks

Each event fills the options it left unset (missing or null) in this order: the event's own options, then context options, then these, then the options the SDK adds (such as process_person_profile: false for an event with no distinct id). beforeSend sees the result and can change it. Values are sent to capture unchanged. Capture drops an event whose option value it cannot read, so a bad value registered here drops every event.

A $identify, $create_alias, $merge_dangerously, $groupidentify, $set or $set_once event whose call leaves process_person_profile unset gets true instead of a value registered here, unless its distinct id is generated.

Example

TypeScript
await client.registerOptions({ cookieless_mode: true })

PostHog.unregisterOptions

unregisterOptions(key): Promise<void>

Remove an option added with registerOptions().

Parameters

ParameterTypeDescription
keystringThe option name to remove

Returns

Promise<void>

PostHog.withContext

withContext<T>(data, fn, options?): T

Run a function with request-scoped context using AsyncLocalStorage so state propagates down function calls and await.

By default, nested contexts inherit parent state while overriding keys locally without mutating the parent. Pass { fresh: true } at request or job boundaries to clear inherited state, and pass { signal } to end a context when an AbortSignal aborts.

Events and exceptions inherit distinctId, sessionId ($session_id, except groupIdentify()), properties, and options. evaluateFlags(), getAllFlags(), getAllFlagsAndPayloads(), and getFeatureFlagResult() read distinctId when omitted. Logs and spans inherit distinctId and sessionId. Pass a UUIDv7 sessionId (such as x-posthog-session-id from posthog-js) to link backend telemetry to Session Replay.

On posthog-node/edge, withContext() runs fn directly without AsyncLocalStorage, so nested calls won't see context data.

Type Parameters

Type Parameter
T

Parameters

ParameterTypeDescription
dataPartial<ContextData>Context data to apply (sessionId, distinctId, properties, options)
fn() => TFunction to run with the context
options?ContextOptionsContext options (fresh: true to clear inherited state, signal to expire on abort)

Returns

T

The return value of the function

Remarks

Context properties and options fill only what an event left unset: the event's own values win, and context values beat register(), registerOptions(), and SDK defaults. beforeSend sees the result and can change it.

On $identify, $create_alias, $merge_dangerously, $groupidentify, $set, and $set_once events, a context process_person_profile option applies only when the distinct ID is generated, and a $process_person_profile property never applies (see registerOptions()).

Example

TypeScript
posthog.withContext({ distinctId: 'user_123' }, () => {
posthog.capture({ event: 'button clicked' })
})

FeatureFlagError

const FeatureFlagError: object

Error type constants for the $feature_flag_error property.

These values are sent in analytics events to track flag evaluation failures. They should not be changed without considering impact on existing dashboards and queries that filter on these values.

Error values: ERRORS_WHILE_COMPUTING: Server returned errorsWhileComputingFlags=true FLAG_MISSING: Requested flag not in API response EVALUATION_FAILED: Requested flag's remote record has no evaluated value LOCAL_EVALUATION_INCONCLUSIVE: Flag has a loaded local definition but local evaluation could not resolve it QUOTA_LIMITED: Rate/quota limit exceeded TIMEOUT: Request timed out CONNECTION_ERROR: Network connection failed apiError: HTTP error with status code (e.g., api_error_500)

Type Declaration

NameType
apiError()(status) => string
CONNECTION_ERROR"connection_error"
ERRORS_WHILE_COMPUTING"errors_while_computing_flags"
EVALUATION_FAILED"evaluation_failed"
FLAG_MISSING"flag_missing"
LOCAL_EVALUATION_INCONCLUSIVE"local_evaluation_inconclusive"
QUOTA_LIMITED"quota_limited"
TIMEOUT"timeout"
UNKNOWN_ERROR"unknown_error"

HTTP_SERVER_REQUEST_COUNT_METRIC

const HTTP_SERVER_REQUEST_COUNT_METRIC: "http.server.request.count" = 'http.server.request.count'

Counter of requests served.

HTTP_SERVER_REQUEST_DURATION_METRIC

const HTTP_SERVER_REQUEST_DURATION_METRIC: "http.server.request.duration" = 'http.server.request.duration'

Duration histogram, in seconds, using the OpenTelemetry HTTP semantic convention name.

uuidv7

const uuidv7: () => string

Generates a UUIDv7 string.

Returns

string

The 8-4-4-4-12 canonical hexadecimal string representation ("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx").

cookieStateToProperties

cookieStateToProperties(state): Record<string, string> | undefined

Converts cookie state into PostHog properties (e.g. $session_id, $device_id).

Parameters

ParameterType
statePostHogCookieState | null

Returns

Record<string, string> | undefined

cookieStoreFromHeader

cookieStoreFromHeader(cookieHeader): CookieStore

Adapts a raw Cookie header string into a CookieStore.

Parameters

ParameterType
cookieHeaderstring

Returns

CookieStore

createEventProcessor

createEventProcessor(_posthog, options?): (event) => any

Creates an event processor for the deprecated Sentry integration.

Parameters

ParameterType
_posthogPostHogBackendClient
options?SentryIntegrationOptions

Returns

(event) => any

Deprecated

This integration is deprecated and will be removed in a future major version. Use PostHog Error Tracking for Node instead: https://posthog.com/docs/error-tracking/installation/node

getPostHogCookieName

getPostHogCookieName(apiKey): string

Returns the PostHog cookie name for the given API key.

PostHog-js stores state in a cookie named ph_<sanitized_token>_posthog. The token is sanitized by replacing + with PL, / with SL, = with EQ.

Parameters

ParameterTypeDescription
apiKeystringThe PostHog project API key

Returns

string

The cookie name string

parsePostHogCookie

parsePostHogCookie(cookieValue): PostHogCookieState | null

Parses a PostHog cookie value and extracts identity information.

The cookie value is a JSON object containing distinct_id and $user_state. A user is considered identified if $user_state is 'identified'.

Parameters

ParameterTypeDescription
cookieValuestringThe raw cookie string value

Returns

PostHogCookieState | null

Parsed identity state, or null if the cookie is missing/invalid

readPostHogCookie

readPostHogCookie(cookies, apiKey): PostHogCookieState | null

Reads and parses the PostHog cookie from a cookie store.

Compatible with Next.js cookies(), request.cookies, and any object with a get(name) method that returns { value: string } | undefined.

Parameters

ParameterType
cookiesCookieStore
apiKeystring

Returns

PostHogCookieState | null

serializePostHogCookie

serializePostHogCookie(anonymousId): string

Serializes an anonymous ID into the JSON format posthog-js expects.

When distinct_id === $device_id, posthog-js treats the user as anonymous.

Parameters

ParameterTypeDescription
anonymousIdstringThe anonymous distinct ID to serialize

Returns

string

JSON string suitable for the PostHog cookie value

setupExpressRequestContext

setupExpressRequestContext(_posthog, app): void

Register Express middleware that binds per-request PostHog context before your routes run.

Reads x-posthog-session-id and x-posthog-distinct-id headers (or the posthog-js cookie when readPostHogCookie is enabled) and attaches $current_url, $request_method, $request_path, $user_agent, and $ip (first x-forwarded-for entry or req.socket.remoteAddress) to events in that request.

Tracing headers are untrusted client data, never authentication, so pass an authenticated distinctId explicitly for authorization or sensitive decisions. Client IP geolocation from $ip also requires disableGeoip: false.

Parameters

ParameterTypeDescription
_posthogPostHogBackendClientPostHog client instance
app{ use: (middleware) => unknown; }Express app or router with .use()
app.use(middleware) => unknown-

Returns

void

Example

TypeScript
import express from 'express'
import { PostHog, setupExpressErrorHandler, setupExpressRequestContext } from 'posthog-node'
const app = express()
const client = new PostHog('<ph_project_api_key>', { host: 'https://us.i.posthog.com' })
setupExpressRequestContext(client, app)
app.get('/', (_req, res) => {
client.capture({ event: 'page_loaded' })
res.send('ok')
})
setupExpressErrorHandler(client, app)

PostHogInterceptor

NestJS interceptor from posthog-node/nestjs that isolates per-request PostHog context with AsyncLocalStorage and optionally captures controller exceptions.

Resolves distinctId in order: getDistinctId(request), then x-posthog-distinct-id (or cookie when readPostHogCookie is enabled), then any outer withContext(). Attaches $current_url, $request_method, $request_path, $user_agent, and $ip.

Tracing headers are untrusted client data, never authentication. Set captureExceptions: true (or { minStatusToCapture }, default 500) to capture errors with $response_status_code.

Example

TypeScript
import { PostHog } from 'posthog-node'
import { PostHogInterceptor } from 'posthog-node/nestjs'
const posthog = new PostHog('<ph_project_api_key>', { host: 'https://us.i.posthog.com' })
app.useGlobalInterceptors(new PostHogInterceptor(posthog, { captureExceptions: true }))

Implements

  • NestInterceptor

Constructors

Constructor

new PostHogInterceptor(posthog, options?): PostHogInterceptor

Create a NestJS interceptor bound to a PostHog client.

Parameters
ParameterTypeDescription
posthogPostHogBackendClientPostHog client instance
options?PostHogInterceptorOptionsException capture and user ID resolution options
Returns

PostHogInterceptor

Methods

intercept()

intercept(context, next): Observable<any>

Wrap an incoming NestJS request in an isolated PostHog context.

Parameters
ParameterType
contextExecutionContext
nextCallHandler
Returns

Observable<any>

Types

ActionStepStringMatching

ActionStepStringMatching = typeof ActionStepStringMatching[keyof typeof ActionStepStringMatching]

Sync with plugin-server/src/types.ts

ActionStepType

ActionStepType = object

Properties

PropertyTypeDescription
event?string-
href?string-
href_matching?ActionStepStringMatchingDefault ActionStepStringMatching.Exact
selector?string-
text?string-
text_matching?ActionStepStringMatchingDefault StringMatching.Exact
url?string-
url_matching?ActionStepStringMatchingDefault StringMatching.Contains

AllFlagsOptions

AllFlagsOptions = BaseFlagEvaluationOptions & object

Type Declaration

NameTypeDescription
flagKeys?string[]Restrict local evaluation, the /flags request, and the returned snapshot to these keys. An empty array returns an empty snapshot without evaluating flags; omitting this option evaluates all flags. evaluateFlags() falls back remotely when a requested key is missing from local definitions unless onlyEvaluateLocally is true. Remote evaluation responses are not cached, so a key missing both locally and remotely costs one /flags request per call.

BaseFlagEvaluationOptions

BaseFlagEvaluationOptions = object

Properties

PropertyTypeDescription
disableGeoip?booleanOverrides the client's disableGeoip setting for this evaluation call.
groupProperties?Record<string, Properties>Group properties keyed by group type for evaluating group-targeted flags.
groupPropertyKeysKnownAbsent?Record<string, string[]>Group property keys you know each group doesn't have, by group type name. A key applies only to its own group type. Otherwise follows personPropertyKeysKnownAbsent, with the 1000-key limit applying to each group type's list.
groups?Record<string, string>Group types and keys to evaluate group-targeted flags against (for example { company: 'acme' }).
onlyEvaluateLocally?booleanSkip remote fallback and omit flags that local definitions cannot resolve.
personProperties?PropertiesPerson properties used instead of stored server properties. Include $geoip_* keys (such as $geoip_country_code and $geoip_subdivision_1_code) to evaluate GeoIP flags using the client's location.
personPropertyKeysKnownAbsent?string[]Person property keys you know this person doesn't have. Local evaluation treats a listed key as absent even when personProperties has a value for it, so is_not_set and the negated operators match and every other supported operator doesn't, without a /flags request. A filter with an operator the SDK can't evaluate locally, or with an operator that needs a value but has none, still falls back to /flags. The list is sent to /flags when evaluation falls back to it. At most 1000 keys, counting duplicates; a longer list throws an error and no flags are evaluated.

BasicSurveyQuestion

BasicSurveyQuestion = SurveyQuestionBase & object

Type Declaration

NameType
typetypeof SurveyQuestionType.Open

BeforeSendFn

BeforeSendFn = (event) => EventMessage | null

Parameters

ParameterType
eventEventMessage

Returns

EventMessage | null

BeforeSendLogFn

BeforeSendLogFn = (record) => CaptureLogOptions | null

Pre-send filter. Inspect, mutate, or drop a captured log record before it enters the rate cap or the buffer. Return the (possibly transformed) record to keep it; return null to drop it.

Configure as a single function or an array. Arrays form a left-to-right chain: each function receives the previous function's return value, and a null from any link short-circuits the chain and drops the record. A function that throws also drops the record (the error is logged).

Parameters

ParameterType
recordCaptureLogOptions

Returns

CaptureLogOptions | null

Example

Redact secrets from log bodies

TypeScript
logs: { beforeSend: (record) => ({ ...record, body: record.body.replace(/token=\S+/g, 'token=[REDACTED]') }) }

BeforeSendMetricFn

BeforeSendMetricFn = (sample) => MetricSample | null

Pre-aggregation filter. Return the (possibly transformed) sample to keep it; return null to drop it. Configure as a single function or an array forming a left-to-right chain; a null from any link drops the sample and a thrown error also drops it (the error is logged).

Parameters

ParameterType
sampleMetricSample

Returns

MetricSample | null

Example

Drop debug metrics in production

TypeScript
metrics: { beforeSend: (m) => (m.name.startsWith('debug_') ? null : m) }

BeforeSpanSendFn

BeforeSpanSendFn = (span) => SpanRecord | null

Experimental

Inspects, edits or drops a finished span. Return null to drop it.

The hook runs synchronously as part of end(); a returned promise is not awaited and the span is dropped.

Subject to change in a minor release.

Parameters

ParameterType
spanSpanRecord

Returns

SpanRecord | null

CallHandler

Type ParameterDefault type
Tany

Methods

handle()

handle(): Observable<T>

Returns

Observable<T>

CaptureDroppedEvent

A single event the server explicitly rejected (drop).

Properties

PropertyType
details?string
uuidstring

CaptureEndpoint

CaptureEndpoint = typeof ANALYTICS_CAPTURE_ENDPOINT | typeof AI_CAPTURE_ENDPOINT

CaptureErrorParams

PropertyTypeDescription
cause?unknownThe underlying transport/HTTP/parse failure, when the whole batch failed.
dropsCaptureDroppedEvent[]Events the server rejected outright (billing/validation).
endpointCaptureEndpointThe capture lane the batch was sent to.
requestIdstring-
retryExhaustedstring[]UUIDs of events still pending retry after the attempt budget was exhausted, or lost to a batch-level failure.

CaptureExceptionOptions

CaptureExceptionOptions = object

Options for captureException() and captureExceptionImmediate().

Properties

PropertyTypeDescription
distinctId?stringThe event's distinct id. Without one, the context distinct id is used, else a personless id.
flags?FeatureFlagEvaluationsA FeatureFlagEvaluations snapshot to attach the same flag context as your other events.
level?SeverityLevelThe exception's severity, sent as $exception_level. An unknown value is ignored. Default 'error'
options?EventOptionsPer-event options, as in capture().
properties?Record<string | number, any>Properties to add to the event. Exception properties the SDK or PostHog owns, such as $exception_list and $exception_level, are ignored: use level to set the level.
uuid?stringOverrides the generated event UUID. Must be a valid UUID.

CaptureLogOptions

PropertyTypeDescription
attributes?LogAttributesPer-log attributes (request-specific context like order_id, duration_ms)
bodystringThe log message body (required)
level?LogSeverityLevelLog severity level (default: 'info')
span_id?stringSpan ID for correlation — 16 hex chars
trace_flags?numberW3C trace flags (default: 0)
trace_id?stringTrace ID for correlation — 32 hex chars

CaptureMetricOptions

Options accepted by posthog.metrics.count/gauge/histogram.

Extended by

  • HistogramOptions

Properties

PropertyTypeDescription
attributes?MetricAttributesLow-cardinality dimensions to filter and group by (e.g. route, plan, region). Each distinct combination is its own series.
unit?stringUnit of the value (e.g. 'ms', 'byte'). Displayed in the Metrics UI and part of the series identity — the same name with two units is two series.

Compression

Enumeration MemberValue
Base64"base64"
GZipJS"gzip-js"

ContextData

PropertyTypeDescription
distinctId?stringDistinct ID applied to events, flag evaluations, logs, and spans inside the context when not passed directly.
options?V1EventOptionsOptions that fill the options an event left unset (missing or null). The event's own options win; these beat options from registerOptions(). A process_person_profile here does not reach $identify, $create_alias, $merge_dangerously, $groupidentify, $set or $set_once events unless their distinct id is generated.
properties?Record<string, any>Properties that fill the keys an event left unset. The event's own values win.
sessionId?stringSession ID (UUIDv7) attached as $session_id on events and sessionId on logs and spans inside the context.

ContextOptions

PropertyTypeDescription
fresh?booleanIf true, replaces the current context entirely. If false, merges with the existing context (new values override existing ones). Default false
signal?AbortSignalEnds this context and its inherited scopes when aborted, without cancelling the callback. An already aborted signal starts no active context. A fresh context has an independent lifetime.

CookieStore

Minimal cookie-reading interface compatible with Next.js cookies(), request.cookies, and plain objects.

Methods

get()

get(name): { value: string; } | undefined

Parameters
ParameterType
namestring
Returns

{ value: string; } | undefined

EmailReactRenderer

Renders react sends: the @react-email/render module, or an object with its render and toPlainText.

Methods

render()

render(element): Promise<string>

Renders a React element to HTML. Typed as any because @react-email/render takes React.ReactNode, which posthog-node doesn't depend on.

Parameters
ParameterType
elementany
Returns

Promise<string>

toPlainText()

toPlainText(html): string

Parameters
ParameterType
htmlstring
Returns

string

EndBranching

EndBranching = object

Properties

PropertyType
typetypeof SurveyQuestionBranchingType.End

EvaluationReason

EvaluationReason = object

Properties

PropertyType
codestring | undefined
condition_indexnumber | undefined
descriptionstring | undefined

EventMessage

EventMessage = object

Properties

PropertyTypeDescription
_originatedFromCaptureException?booleanInternal flag set by captureException() to indicate this $exception event originated from the proper exception capture path. Used to warn users who call capture() with '$exception' directly.
disableGeoip?booleanOverrides the client's disableGeoip setting for this event.
distinctId?stringThe event's distinct ID. When missing, empty, or whitespace, uses withContext(), else generates a UUIDv7 and sets options.process_person_profile: false.
eventstringEvent name (such as 'order_placed' or '$pageview'). Must be 200 UTF-8 bytes or fewer.
flags?FeatureFlagEvaluationsAttach feature flag values evaluated via posthog.evaluateFlags() to this event. Prefer this over sendFeatureFlags so the event carries the exact values your code branched on without a hidden /flags request.
groups?Record<string, string | number>Group types and keys to associate with this event (for example { company: 'acme' }, up to 5 per project).
options?EventOptionsProcessing options sent with this event to capture v1.
properties?Record<string | number, any>Event properties (also accepts $set, $set_once, and $current_url).
sendFeatureFlags?boolean | SendFeatureFlagsOptionsDeprecated Use the flags option with a FeatureFlagEvaluations object obtained from posthog.evaluateFlags() instead. sendFeatureFlags fires a separate /flags request on capture and may return different values than the ones the code branched on.
timestamp?DateIf provided, overrides the auto-generated timestamp. UTC is preferred; non-UTC input is converted to UTC.
uuid?stringIf provided overrides the auto-generated event UUID. Must be a valid UUID.

EventOptions

EventOptions = V1EventOptions

Processing options sent with an event to capture v1.

ExceptionCaptureOptions

PropertyTypeDescription
minStatusToCapture?numberMinimum HTTP status code to capture. Exceptions with a lower status (e.g. 4xx) are skipped. Default 500

ExceptionRateLimiterConfig

Shared configuration for the error tracking burst-protection rate limiter.

Burst protection is scoped per exception type — the limiter is keyed by exception type, so each distinct $exception type gets its own token bucket and there is no aggregate cap across all types. It applies only to autocaptured exceptions; manual captureException calls are never rate limited. These options let customers with high-cardinality exception types tune the per-type allowance, and are shared between the browser and Node SDKs.

Properties

PropertyTypeDescription
exceptionRateLimiterBucketSize?numberADVANCED: alters the bucket size for the error tracking rate limiter's token bucket. Normally only altered alongside PostHog support guidance. Accepts values between 0 and 100. Default 10
exceptionRateLimiterRefillRate?numberADVANCED: alters the refill rate for the error tracking rate limiter's token bucket. Normally only altered alongside PostHog support guidance. Accepts values between 0 and 100. Default 1

ExecutionContext

switchToHttp()

switchToHttp(): HttpArgumentsHost

Returns

HttpArgumentsHost

ExpressErrorMiddleware

ExpressErrorMiddleware = (error, req, res, next) => void

Parameters

ParameterType
errorMiddlewareError
reqRequest
resResponse
next(error) => void

Returns

void

ExpressMiddleware

ExpressMiddleware = (req, res, next) => void

Parameters

ParameterType
reqRequest
resResponse
next() => void

Returns

void

FeatureFlagBucketingIdentifier

FeatureFlagBucketingIdentifier = "distinct_id" | "device_id" | "" | null

FeatureFlagCondition

FeatureFlagCondition = object

Properties

PropertyType
aggregation_group_type_index?number | null
propertiesFlagProperty[]
rollout_percentage?number
variant?string

FeatureFlagDetail

FeatureFlagDetail = object

Properties

PropertyType
enabledboolean
failed?boolean
keystring
metadataFeatureFlagMetadata | undefined
reasonEvaluationReason | undefined
variantstring | undefined

FeatureFlagErrorType

FeatureFlagErrorType = typeof FeatureFlagError[Exclude<keyof typeof FeatureFlagError, "apiError">] | ReturnType<typeof apiError> | string

FeatureFlagEvaluationRuntime

FeatureFlagEvaluationRuntime = "all" | "client" | "server"

Where a feature flag is meant to be evaluated. Set per flag in PostHog and carried on every locally cached flag definition. all means the flag suits both client-side and server-side evaluation, so it matches either runtime.

FeatureFlagMetadata

FeatureFlagMetadata = object

Properties

PropertyTypeDescription
descriptionstring | undefined-
has_experiment?booleanWhether the flag is linked to an experiment. Absent when the server does not report it.
idnumber | undefined-
payloadstring | undefined-
versionnumber | undefined-

FeatureFlagOverrideOptions

FeatureFlagOverrideOptions = object

Properties

PropertyTypeDescription
flags?false | string[] | Record<string, FeatureFlagValue>Flag overrides. Can be: - false to clear flag overrides - string[] to enable a list of flags - Record<string, FeatureFlagValue> to set specific values/variants
payloads?false | Record<string, JsonType>Payload overrides for flags. - false to clear payload overrides - Record<string, JsonType> to set specific payloads

FeatureFlagResult

FeatureFlagResult = object

Result of evaluating a feature flag, including its value and payload.

Properties

PropertyTypeDescription
enabledbooleanWhether the returned feature flag evaluation is enabled. false is a conclusive off result.
keystring-
payloadJsonType | undefined-
reason?stringPostHog's evaluation explanation, when available.
reasonCode?stringStable evaluation reason code, when available (for example, flag_disabled).
variantstring | undefined-

FeatureFlagValue

FeatureFlagValue = string | boolean

FlagDefinitionCacheData

Represents the complete set of feature flag data needed for local evaluation.

This includes flag definitions, group type mappings, and cohort property groups. Newly published data includes snake_case keys and camelCase aliases so existing providers and older Node SDKs can continue to read the same cache.

Properties

PropertyTypeDescription
cohortsRecord<string, PropertyGroup>Cohort property groups for local evaluation
flagsPostHogFeatureFlag[]Array of feature flag definitions
group_type_mapping?Record<string, string>Mapping of group type index to group name, using the flag-definitions endpoint's field name.
groupTypeMappingRecord<string, string>Legacy alias for group_type_mapping, retained for existing providers and cache readers.
minimal_flag_called_events?booleanServer-controlled gate for minimal $feature_flag_called events, from the top-level minimal_flag_called_events field of the flag-definitions payload. If neither this field nor its legacy alias is present, full events are sent.
minimalFlagCalledEvents?booleanLegacy alias for minimal_flag_called_events.
property_matching_version?numberTop-level definitions matching version; absent in older caches means legacy matching.
propertyMatchingVersion?numberLegacy alias for property_matching_version.

FlagDefinitionCacheInput

FlagDefinitionCacheInput = FlagDefinitionCacheData | Omit<FlagDefinitionCacheData, "groupTypeMapping"> & object

Cache reads accept endpoint-shaped snake_case data or older camelCase data. When both forms are present, snake_case takes precedence.

FlagDefinitionCacheProvider

Provider interface for caching feature flag definitions.

Implementations can use this to control when flag definitions are fetched and how they're cached (Redis, database, filesystem, etc.).

This interface is designed for server-side environments where multiple workers need to share flag definitions and coordinate fetching to reduce API calls. Without a secretKey or personalApiKey, instances are cache-only readers: each refresh reads cached definitions without calling shouldFetchFlagDefinitions or publishing data. Instances with a credential coordinate fetching and publish fresh definitions.

All methods may throw errors - the poller will catch and log them gracefully, ensuring cache provider errors never break flag evaluation.

Example

typescript
import type { FlagDefinitionCacheData, FlagDefinitionCacheInput, FlagDefinitionCacheProvider } from 'posthog-node'
class RedisFlagCache implements FlagDefinitionCacheProvider<FlagDefinitionCacheInput> {
constructor(private redis: Redis, private teamKey: string) { }
async getFlagDefinitions(): Promise<FlagDefinitionCacheInput | undefined> {
const cached = await this.redis.get(`posthog:flags:${this.teamKey}`)
return cached ? JSON.parse(cached) : undefined
}
async shouldFetchFlagDefinitions(): Promise<boolean> {
// Acquire distributed lock - only one worker fetches
const acquired = await this.redis.set(`posthog:flags:${this.teamKey}:lock`, '1', 'EX', 60, 'NX')
return acquired === 'OK'
}
async onFlagDefinitionsReceived(data: FlagDefinitionCacheData): Promise<void> {
await this.redis.set(`posthog:flags:${this.teamKey}`, JSON.stringify(data), 'EX', 300)
await this.redis.del(`posthog:flags:${this.teamKey}:lock`)
}
async shutdown(): Promise<void> {
await this.redis.del(`posthog:flags:${this.teamKey}:lock`)
}
}

Type Parameters

Type ParameterDefault typeDescription
CacheData extends FlagDefinitionCacheInputFlagDefinitionCacheDataThe shape returned by cache reads. Use FlagDefinitionCacheInput to accept snake_case entries as well as legacy camelCase entries.

Methods

getFlagDefinitions()

getFlagDefinitions(): CacheData | Promise<CacheData | undefined> | undefined

Retrieve cached flag definitions.

Called when the poller is refreshing in-memory flag definitions. If this returns undefined (or throws an error), the poller will fetch fresh data from the PostHog API if no flag definitions are in memory and a secretKey or personalApiKey is configured. Otherwise, existing in-memory definitions are retained until the next refresh.

Returns

CacheData | Promise<CacheData | undefined> | undefined

cached definitions if available, undefined if cache is empty

Throws

if an error occurs while accessing the cache (error will be logged)

onFlagDefinitionsReceived()

onFlagDefinitionsReceived(data): void | Promise<void>

Called after successfully receiving new flag definitions from PostHog.

Store the definitions in your cache backend here. This is called only after a successful API response with valid flag data.

If this method throws, the error is logged but flag definitions are still stored in memory, ensuring local evaluation can still be performed.

Parameters
ParameterTypeDescription
dataFlagDefinitionCacheDataThe complete flag definition data from PostHog
Returns

void | Promise<void>

Throws

if storage backend is unavailable (error will be logged)

shouldFetchFlagDefinitions()

shouldFetchFlagDefinitions(): boolean | Promise<boolean>

Determines whether this instance should fetch new flag definitions.

Called only when a secretKey or personalApiKey is configured. Cache-only readers skip this method and read cached definitions directly on each refresh. Use this to implement distributed coordination (e.g., via distributed locks) to ensure only one credentialed instance fetches at a time in a multi-worker setup.

When multiple workers share a cache, typically only one should fetch while others use cached data. Implementations can use Redis locks, database locks, or other coordination mechanisms.

Returns

boolean | Promise<boolean>

true if this instance should fetch, false to skip and read cache

Throws

if coordination backend is unavailable (error will be logged, fetch continues)

shutdown()

shutdown(): void | Promise<void>

Called when the PostHog client shuts down.

Release any held locks, close connections, or clean up resources here.

Both sync and async cleanup are supported. Async cleanup has a timeout (default 30s, configurable via client shutdown options) to prevent the process shutdown from hanging indefinitely.

Returns

void | Promise<void>

Promise that resolves when cleanup is complete, or void for sync cleanup

FlagEvaluationOptions

FlagEvaluationOptions = BaseFlagEvaluationOptions & object

Type Declaration

NameTypeDescription
sendFeatureFlagEvents?booleanWhether this call sends $feature_flag_called, overriding the client's sendFeatureFlagEvent option.

FlagProperty

FlagProperty = object

Properties

PropertyType
dependency_chain?string[]
keystring
negation?boolean
operator?string
type?string
valueFlagPropertyValue

FlagPropertyValue

FlagPropertyValue = string | number | (string | number)[] | boolean

GroupIdentifyMessage

GroupIdentifyMessage = object

Properties

PropertyTypeDescription
disableGeoip?booleanOverrides the client's disableGeoip setting for this event.
distinctId?stringThe event's distinct ID. When missing, empty, or whitespace, uses withContext(), then $<groupType>_<groupKey>.
groupKeystringUnique identifier for the group within groupType.
groupTypestringGroup type name (such as 'company'). Projects support up to 5 group types.
options?EventOptionsProcessing options sent with this event to capture v1.
properties?Record<string | number, any>Group properties ($group_set). Set name for the display name in PostHog.

HistogramOptions

Options accepted by posthog.metrics.histogram.

Extends

  • CaptureMetricOptions

Properties

PropertyTypeDescriptionInherited from
attributes?MetricAttributesLow-cardinality dimensions to filter and group by (e.g. route, plan, region). Each distinct combination is its own series.CaptureMetricOptions.attributes
bounds?number[]Upper bucket boundaries, finite and strictly increasing. A value lands in the first bucket whose boundary is greater than or equal to it, and values above the last boundary land in an overflow bucket. Defaults to the OpenTelemetry defaults [0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000]. The first sample of a histogram (name and unit) fixes its bounds until the client resets. A later sample that passes different bounds is recorded in the fixed buckets and logs a warning, once per flush window. A sample with invalid bounds is dropped with a warning. The client fixes the bounds of at most maxSeriesPerFlush histograms. Past that limit, the client drops samples of a new histogram that pass bounds other than the defaults, and logs one warning. Each client fixes bounds on its own. PostHog stores one set of bounds per histogram series and reads every client's counts against it. Every client must therefore pass the same bounds for the same histogram.-
unit?stringUnit of the value (e.g. 'ms', 'byte'). Displayed in the Metrics UI and part of the series identity — the same name with two units is two series.CaptureMetricOptions.unit

HonoContextLike

The slice of a Hono Context the middleware uses, so hono is not a dependency.

Properties

PropertyTypeDescription
error?unknownSet by Hono when a handler threw and its error handler produced the response.
reqobject-
req.rawRequest-
req.routePathstring-
resResponse-

HttpArgumentsHost

getRequest()

getRequest<T>(): T

Type Parameters
Type ParameterDefault type
Tany
Returns

T

getResponse()

getResponse<T>(): T

Type Parameters
Type ParameterDefault type
Tany
Returns

T

IdentifyMessage

IdentifyMessage = object

Properties

PropertyTypeDescription
disableGeoip?booleanOverrides the client's disableGeoip setting for this event.
distinctIdstringUser distinct ID matching your frontend posthog.identify() call.
options?EventOptionsProcessing options sent with this event to capture v1.
properties?Record<string | number, any>Person properties to set directly, or via $set, $set_once, and $anon_distinct_id.

InstrumentRequestOptions

PropertyTypeDescription
getRoute?(request, response) => string | undefinedThe matched route pattern (/users/:id), once the handler has run. Used to name the span and as the http.route metric attribute. Without it the span is named after the method only, so raw paths never become high-cardinality span names or metric series.
ignore?(request) => booleanSkip instrumentation (health checks, for example). The handler still runs, with no span or metrics.

IPostHog

PropertyModifierTypeDescription
emailsreadonlyEmailsDescription The posthog.emails API: sends transactional email from PostHog templates or from content your code rendered, reads send status, and sets topic preferences. Needs secretKey.
metricsreadonlyMetricsDescription The posthog.metrics API: a statsd-style pre-aggregating metrics client (count, gauge, histogram) — alpha. Samples are folded into per-series aggregates in memory and flushed periodically. Configure via the metrics client option.

Methods

alias()

alias(data): void

Queue a $create_alias event linking alias (the previous or secondary ID) to distinctId (the primary user ID).

Parameters
ParameterTypeDescription
data{ alias: string; disableGeoip?: boolean; distinctId: string; options?: V1EventOptions; }Primary distinctId, previous alias, and optional disableGeoip or options
data.aliasstring-
data.disableGeoip?boolean-
data.distinctIdstring-
data.options?V1EventOptions-
Returns

void

aliasImmediate()

aliasImmediate(data): Promise<void>

Send a $create_alias event immediately to link alias to distinctId.

Parameters
ParameterTypeDescription
data{ alias: string; disableGeoip?: boolean; distinctId: string; options?: V1EventOptions; }Primary distinctId, previous alias, and optional disableGeoip or options
data.aliasstring-
data.disableGeoip?boolean-
data.distinctIdstring-
data.options?V1EventOptions-
Returns

Promise<void>

capture()

capture(props): void

Queue a custom event in memory to send asynchronously.

Parameters
ParameterTypeDescription
propsEventMessageEvent payload including event, optional distinctId, properties, groups, flags, and options
Returns

void

captureAi()

captureAi(props): string | undefined

Capture an AI event on the dedicated AI capture endpoint (/i/v1/ai/events).

Beta: the signature is stable, while operational limits (per-event size cap, batching, endpoint) may change without notice. Delivery is async. The payload is sent as given, except that an event whose properties exceed the per-event size cap is sent without its content properties.

Parameters
ParameterTypeDescription
propsEventMessageAI event payload including event, optional distinctId, properties, groups, flags, and options
Returns

string | undefined

The event UUID, or undefined when the client is disabled

captureAiImmediate()

captureAiImmediate(props): Promise<string | undefined>

Capture an AI event on the dedicated AI capture endpoint (/i/v1/ai/events) and wait for the send attempt to settle.

Parameters
ParameterTypeDescription
propsEventMessageAI event payload including event, optional distinctId, properties, groups, flags, and options
Returns

Promise<string | undefined>

The event UUID, or undefined when the client is disabled

captureException()

captureException(error, options?): void

Parameters
ParameterTypeDescription
errorunknownThe error to capture.
options?CaptureExceptionOptionsOptional distinct id, properties, options, uuid, flags snapshot and level.
Returns

void

Description

Capture an exception as a $exception event.

captureExceptionImmediate()

captureExceptionImmediate(error, options?): Promise<void>

Parameters
ParameterTypeDescription
errorunknownThe error to capture.
options?CaptureExceptionOptionsOptional distinct id, properties, options, uuid, flags snapshot and level.
Returns

Promise<void>

Description

Capture an exception as a $exception event immediately.

captureImmediate()

captureImmediate(props): Promise<void>

Capture an event and wait for the HTTP send attempt to settle. Use in short-lived runtimes where the process can freeze before a background flush.

Don't mix queued capture() and captureImmediate() when event order matters.

Parameters
ParameterTypeDescription
propsEventMessageEvent payload including event, optional distinctId, properties, groups, flags, and options
Returns

Promise<void>

evaluateFlags()
Call Signature

evaluateFlags(options?): Promise<FeatureFlagEvaluations>

Parameters
ParameterTypeDescription
options?AllFlagsOptionsOptional configuration for flag evaluation. flagKeys scopes local evaluation, the /flags request, and the returned snapshot. Missing local keys trigger fallback unless onlyEvaluateLocally is true.
Returns

Promise<FeatureFlagEvaluations>

Description

Evaluate all feature flags for a user in a single call and return a FeatureFlagEvaluations snapshot. Branch on .isEnabled() / .getFlag(), then pass the same snapshot to capture() via the flags option so events carry the exact flag values the code branched on.

Prefer this over calling isFeatureEnabled() / getFeatureFlag() repeatedly and over capture({ sendFeatureFlags: true }) — it avoids multiple /flags requests per incoming request.

Example
TypeScript
const flags = await posthog.evaluateFlags('user_123', { personProperties: { plan: 'enterprise' } })
if (flags.isEnabled('new-dashboard')) {
renderNewDashboard()
}
posthog.capture({ distinctId: 'user_123', event: 'page_viewed', flags })

Local evaluation resolves cached inactive definitions to false. Remote evaluation omits globally inactive flags, so those keys are absent when no local definition is available.

Call Signature

evaluateFlags(distinctId, options?): Promise<FeatureFlagEvaluations>

Parameters
ParameterTypeDescription
distinctIdstringThe user's distinct ID
options?AllFlagsOptionsOptional configuration for flag evaluation. flagKeys scopes local evaluation, the /flags request, and the returned snapshot. Missing local keys trigger fallback unless onlyEvaluateLocally is true.
Returns

Promise<FeatureFlagEvaluations>

Description

Evaluate all feature flags for a specific user.

getActiveSpan()

getActiveSpan(): Span | null

Experimental

Returns

Span | null

Description

The span currently active on this async execution path, or null outside any withSpan callback. Subject to change in a minor release.

getAllFlags()
Call Signature

getAllFlags(options?): Promise<Record<string, FeatureFlagValue>>

Parameters
ParameterType
options?AllFlagsOptions
Returns

Promise<Record<string, FeatureFlagValue>>

Description

Get all feature flag values using distinctId from withContext().

Call Signature

getAllFlags(distinctId, options?): Promise<Record<string, FeatureFlagValue>>

Parameters
ParameterTypeDescription
distinctIdstringThe user's distinct ID
options?AllFlagsOptionsOptional configuration for flag evaluation
Returns

Promise<Record<string, FeatureFlagValue>>

Promise that resolves to a record of flag keys and their values

Description

Get all feature flag values for a specific user.

getAllFlagsAndPayloads()
Call Signature

getAllFlagsAndPayloads(options?): Promise<Partial<Pick<PostHogFlagsResponse, "featureFlags" | "featureFlagPayloads">>>

Parameters
ParameterType
options?AllFlagsOptions
Returns

Promise<Partial<Pick<PostHogFlagsResponse, "featureFlags" | "featureFlagPayloads">>>

Description

Get all feature flag values and payloads using distinctId from withContext().

Call Signature

getAllFlagsAndPayloads(distinctId, options?): Promise<Partial<Pick<PostHogFlagsResponse, "featureFlags" | "featureFlagPayloads">>>

Parameters
ParameterTypeDescription
distinctIdstringThe user's distinct ID
options?AllFlagsOptionsOptional configuration for flag evaluation
Returns

Promise<Partial<Pick<PostHogFlagsResponse, "featureFlags" | "featureFlagPayloads">>>

Promise that resolves to flags and payloads

Description

Get all feature flag values and payloads for a specific user.

getContext()

getContext(): ContextData | undefined

Returns

ContextData | undefined

The current context data, or undefined if no context is set

Description

Get the current context data.

getFeatureFlag()

getFeatureFlag(key, distinctId, options?): Promise<FeatureFlagValue | undefined>

Parameters
ParameterTypeDescription
keystringthe unique key of your feature flag
distinctIdstringthe current unique id
options?{ groupProperties?: Record<string, Properties>; groupPropertyKeysKnownAbsent?: Record<string, string[]>; groups?: Record<string, string>; onlyEvaluateLocally?: boolean; personProperties?: Properties; personPropertyKeysKnownAbsent?: string[]; sendFeatureFlagEvents?: boolean; }-
options.groupProperties?Record<string, Properties>-
options.groupPropertyKeysKnownAbsent?Record<string, string[]>-
options.groups?Record<string, string>-
options.onlyEvaluateLocally?boolean-
options.personProperties?Properties-
options.personPropertyKeysKnownAbsent?string[]-
options.sendFeatureFlagEvents?boolean-
Returns

Promise<FeatureFlagValue | undefined>

true or a variant string if the flag evaluates on, false if it conclusively evaluates off, or undefined if no result is available. Local evaluation resolves cached inactive definitions to false; remote evaluation omits globally inactive flags, leaving no result.

Description

PostHog feature flags (https://posthog.com/docs/features/feature-flags) allow you to safely deploy and roll back new features. Once you've created a feature flag in PostHog, you can use this method to check if the flag is on for a given user, allowing you to create logic to turn features on and off for different user groups or individual users.

Deprecated

Use IPostHog.evaluateFlags and call flags.getFlag(key) on the returned snapshot. Will be removed in the next major version.

getFeatureFlagPayload()

getFeatureFlagPayload(key, distinctId, matchValue?, options?): Promise<JsonType | undefined>

Parameters
ParameterTypeDescription
keystringthe unique key of your feature flag
distinctIdstringthe current unique id
matchValue?FeatureFlagValueThe flag value previously obtained from calling getFeatureFlag(). Can be a string or boolean. To avoid extra network calls, pass this parameter when you can.
options?{ groupPropertyKeysKnownAbsent?: Record<string, string[]>; onlyEvaluateLocally?: boolean; personPropertyKeysKnownAbsent?: string[]; }-
options.groupPropertyKeysKnownAbsent?Record<string, string[]>-
options.onlyEvaluateLocally?boolean-
options.personPropertyKeysKnownAbsent?string[]-
Returns

Promise<JsonType | undefined>

payload of a json type object

Description

Retrieves payload associated with the specified flag and matched value that is passed in.

IMPORTANT: The matchValue parameter should be the value you previously obtained from getFeatureFlag(). If matchValue isn't passed (or is undefined), this method will automatically call getFeatureFlag() internally to fetch the flag value, which could result in a network call to the PostHog server if this flag can not be evaluated locally. This means that omitting matchValue will potentially:

  • Bypass local evaluation
  • Count as an additional flag evaluation against your quota
  • Impact performance due to the extra network request

Example usage:

JavaScript
const flagValue = await client.getFeatureFlag('my-flag', distinctId);
const payload = await client.getFeatureFlagPayload('my-flag', distinctId, flagValue);
Deprecated

Use IPostHog.evaluateFlags and call flags.getFlagPayload(key) on the returned snapshot. Will be removed in the next major version.

getFeatureFlagResult()
Call Signature

getFeatureFlagResult(key, options?): Promise<FeatureFlagResult | undefined>

Parameters
ParameterType
keystring
options?FlagEvaluationOptions
Returns

Promise<FeatureFlagResult | undefined>

Description

Get a feature flag result using distinctId from withContext().

Call Signature

getFeatureFlagResult(key, distinctId, options?): Promise<FeatureFlagResult | undefined>

Parameters
ParameterTypeDescription
keystringThe feature flag key
distinctIdstringThe user's distinct ID
options?FlagEvaluationOptionsOptional configuration for flag evaluation
Returns

Promise<FeatureFlagResult | undefined>

Promise that resolves to the flag result or undefined

Description

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.

Example
TypeScript
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)
}
groupIdentify()

groupIdentify(data): void

Queue a $groupidentify event to create or update group properties (up to 5 group types per project). Set name in properties for the UI display name.

Parameters
ParameterTypeDescription
dataGroupIdentifyMessageGroup identify payload with groupType, groupKey, optional properties, distinctId, and options
Returns

void

groupIdentifyImmediate()

groupIdentifyImmediate(data): Promise<void>

Send a $groupidentify event immediately and wait for the HTTP send attempt to settle.

Parameters
ParameterTypeDescription
dataGroupIdentifyMessageGroup identify payload with groupType, groupKey, optional properties, distinctId, and options
Returns

Promise<void>

identify()

identify(data): void

Queue an $identify event setting person properties for distinctId. Match the distinctId passed to frontend posthog.identify() so client and server activity join to one person.

Parameters
ParameterTypeDescription
dataIdentifyMessageIdentify payload with distinctId and optional properties ($set, $set_once, $anon_distinct_id)
Returns

void

identifyImmediate()

identifyImmediate(data): Promise<void>

Send an $identify event immediately and wait for the HTTP send attempt to settle.

Parameters
ParameterTypeDescription
dataIdentifyMessageIdentify payload with distinctId and optional properties ($set, $set_once, $anon_distinct_id)
Returns

Promise<void>

isFeatureEnabled()

isFeatureEnabled(key, distinctId, options?): Promise<boolean | undefined>

Parameters
ParameterTypeDescription
keystringthe unique key of your feature flag
distinctIdstringthe current unique id
options?{ groupProperties?: Record<string, Properties>; groupPropertyKeysKnownAbsent?: Record<string, string[]>; groups?: Record<string, string>; onlyEvaluateLocally?: boolean; personProperties?: Properties; personPropertyKeysKnownAbsent?: string[]; sendFeatureFlagEvents?: boolean; }-
options.groupProperties?Record<string, Properties>-
options.groupPropertyKeysKnownAbsent?Record<string, string[]>-
options.groups?Record<string, string>-
options.onlyEvaluateLocally?boolean-
options.personProperties?Properties-
options.personPropertyKeysKnownAbsent?string[]-
options.sendFeatureFlagEvents?boolean-
Returns

Promise<boolean | undefined>

true if the flag evaluates on, false if it conclusively evaluates off, or undefined if no result is available. Local evaluation resolves cached inactive definitions to false; remote evaluation omits globally inactive flags, leaving no result.

Description

PostHog feature flags (https://posthog.com/docs/features/feature-flags) allow you to safely deploy and roll back new features. Once you've created a feature flag in PostHog, you can use this method to check if the flag is on for a given user, allowing you to create logic to turn features on and off for different user groups or individual users.

Deprecated

Use IPostHog.evaluateFlags and call flags.isEnabled(key) on the returned snapshot. Will be removed in the next major version.

isLocalEvaluationReady()

isLocalEvaluationReady(): boolean

Returns

boolean

true if local evaluation is ready, false if it's not.

Description

Returns true if local evaluation is ready, false if it's not.

overrideFeatureFlags()

overrideFeatureFlags(overrides): void

Parameters
ParameterTypeDescription
overridesOverrideFeatureFlagsOptionsFlag overrides configuration
Returns

void

Description

Override feature flags locally. Useful for testing and local development. Overridden flags take precedence over both local evaluation and remote evaluation.

Example
TypeScript
// Clear all overrides
posthog.overrideFeatureFlags(false)
// Enable a list of flags (sets them to true)
posthog.overrideFeatureFlags(['flag-a', 'flag-b'])
// Set specific flag values/variants
posthog.overrideFeatureFlags({ 'my-flag': 'variant-a', 'other-flag': true })
// Set both flags and payloads
posthog.overrideFeatureFlags({
flags: { 'my-flag': 'variant-a' },
payloads: { 'my-flag': { discount: 20 } }
})
reloadFeatureFlags()

reloadFeatureFlags(): Promise<void>

Returns

Promise<void>

Description

Force an immediate reload of the polled feature flags. Please note that they are already polled automatically at a regular interval.

setPersonProperties()

setPersonProperties(data): void

Queue a $set event to set or set-once properties on a person profile.

Parameters
ParameterTypeDescription
dataSetPersonPropertiesMessageDistinct ID and properties (properties for $set, propertiesOnce for $set_once)
Returns

void

shutdown()

shutdown(shutdownTimeoutMs?): Promise<void>

Parameters
ParameterTypeDescription
shutdownTimeoutMs?numberThe shutdown timeout, in milliseconds. Defaults to 30000 (30s).
Returns

Promise<void>

Description

Flushes the events still in the queue and clears the feature flags poller to allow for a clean shutdown.

startSpan()

startSpan(name, options?): Span

Experimental

Parameters
ParameterType
namestring
options?StartSpanOptions
Returns

Span

Description

Starts a span without making it active, for work that can't wrap a callback. Prefer withSpan. Always returns a handle — an inert one when tracing is off — so calling code never has to branch. Subject to change in a minor release.

unsetPersonProperties()

unsetPersonProperties(data): void

Queue a $set event carrying $unset to remove properties from a person profile.

Parameters
ParameterTypeDescription
dataUnsetPersonPropertiesMessageDistinct ID and property key or array of keys to remove
Returns

void

waitForLocalEvaluationReady()

waitForLocalEvaluationReady(timeoutMs?): Promise<boolean>

Parameters
ParameterTypeDescription
timeoutMs?numberMaximum time to wait in milliseconds. Defaults to 30 seconds.
Returns

Promise<boolean>

A promise that resolves to true if local evaluation is ready, false if the timeout was reached.

Description

Waits for local evaluation to be ready, with an optional timeout.

withContext()

withContext<T>(data, fn, options?): T

Type Parameters
Type Parameter
T
Parameters
ParameterTypeDescription
dataPartial<ContextData>Context data to apply (sessionId, distinctId, properties, options)
fn() => TFunction to run with the context
options?ContextOptionsContext options (fresh)
Returns

T

The return value of the function

Description

Run a function with specific context that will be applied to all events captured within that context.

withSpan()
Call Signature

withSpan<T>(name, fn): T

Experimental

Type Parameters
Type Parameter
T
Parameters
ParameterType
namestring
fn(span) => T
Returns

T

Description

Runs a callback with a span active for its duration and ends the span at return (sync) or settle (async). Spans started inside nest automatically; a throw or rejection is recorded on the span and rethrown unchanged. Subject to change in a minor release.

Call Signature

withSpan<T>(name, options, fn): T

Type Parameters
Type Parameter
T
Parameters
ParameterType
namestring
optionsStartSpanOptions
fn(span) => T
Returns

T

JsonType

JsonType = string | number | boolean | null | {[key: string]: JsonType; } | JsonType[] | JsonType[]

LinkSurveyQuestion

LinkSurveyQuestion = SurveyQuestionBase & object

Type Declaration

NameType
link?string | null
typetypeof SurveyQuestionType.Link

LogAttributes

LogAttributes = Record<string, LogAttributeValue>

LogAttributeValue

LogAttributeValue = string | number | boolean | null | undefined | unknown[] | Record<string, unknown>

Logger

Per-level convenience logger. Each method captures a structured log record at the corresponding severity, equivalent to posthog.captureLog({ body, level, attributes }).

Example

TypeScript
posthog.logger.info('checkout completed', { order_id: 'ord_789' })
posthog.logger.error('payment failed', { code: 'E001' })

Methods

debug()

debug(body, attributes?): void

Debug-level detail. Verbose, only useful while diagnosing.

Parameters
ParameterType
bodystring
attributes?LogAttributes
Returns

void

error()

error(body, attributes?): void

Error. Operation failed; the app may continue.

Parameters
ParameterType
bodystring
attributes?LogAttributes
Returns

void

fatal()

fatal(body, attributes?): void

Fatal. Operation failed; the app likely cannot continue.

Parameters
ParameterType
bodystring
attributes?LogAttributes
Returns

void

info()

info(body, attributes?): void

Informational. Normal app events worth recording.

Parameters
ParameterType
bodystring
attributes?LogAttributes
Returns

void

trace()

trace(body, attributes?): void

Lowest severity. Trace-level diagnostic detail.

Parameters
ParameterType
bodystring
attributes?LogAttributes
Returns

void

warn()

warn(body, attributes?): void

Warning. Something unexpected but non-fatal.

Parameters
ParameterType
bodystring
attributes?LogAttributes
Returns

void

LogSeverityLevel

LogSeverityLevel = "trace" | "debug" | "info" | "warn" | "error" | "fatal"

Log capture types

MetricAttributes

MetricAttributes = Record<string, MetricAttributeValue>

MetricAttributeValue

MetricAttributeValue = string | number | boolean

Metric attribute values are restricted to scalars. Every distinct attribute-value combination creates a new metric series, so high-cardinality values (user IDs, request IDs, URLs) must not be used as attributes — put those on logs or events instead.

Metrics

The public posthog.metrics API.

Example

TypeScript
posthog.metrics.count('orders_created', 1)
posthog.metrics.gauge('active_connections', 42)
posthog.metrics.histogram('api_latency', 187, { unit: 'ms' })

Methods

count()

count(name, value?, options?): void

Add to a counter — things that only go up (orders, clicks, API calls). Value defaults to 1.

Parameters
ParameterType
namestring
value?number
options?CaptureMetricOptions
Returns

void

flush()

flush(): Promise<void>

Send everything aggregated so far without waiting for the flush interval.

Returns

Promise<void>

gauge()

gauge(name, value, options?): void

Record the current value of something that goes up and down (queue depth, connections).

Parameters
ParameterType
namestring
valuenumber
options?CaptureMetricOptions
Returns

void

histogram()

histogram(name, value, options?): void

Record one observation of a distribution (latency, payload size).

Parameters
ParameterType
namestring
valuenumber
options?HistogramOptions
Returns

void

MetricSample

A captured metric as seen by beforeSend, before aggregation. Mutating name, value, unit, attributes, or bounds changes what gets aggregated; returning null drops the sample.

Properties

PropertyTypeDescription
attributes?MetricAttributes-
bounds?number[]Histogram bucket boundaries. See HistogramOptions.bounds. Only histograms use them.
namestring-
typeMetricType-
unit?string-
valuenumber-

MetricsConfig

Options for the posthog.metrics API (count, gauge, histogram). Shared by every SDK; browser-only options live in BrowserMetricsConfig.

Properties

PropertyTypeDescription
beforeSend?BeforeSendMetricFn | BeforeSendMetricFn[]Pre-aggregation filter for metric samples, as a single function or a left-to-right chain. Each function inspects, mutates, or drops a sample (return null to drop) before it is aggregated.
environment?stringThe deployment environment for metric series (e.g. 'production', 'staging'). Maps to the OTel resource attribute 'deployment.environment'.
flushIntervalMs?numberHow often the aggregated window is flushed, in milliseconds. Samples are folded into per-series aggregates in memory between flushes — one data point per series per window, no matter how many calls. The browser SDK defaults to 60000: every tab of an app writes to the same series, so a longer window keeps busy series under the backend's per-series point limit. Default 10000 (60000 in the browser)
maxSeriesPerFlush?numberCardinality guardrail: maximum distinct series (name + type + unit + attribute combination) held per flush window. Samples for series beyond the cap are dropped with a single warning per window. Default 1000
resourceAttributes?MetricAttributesAdditional resource attributes applied to every metrics batch. These describe the service/deployment, not individual series. Named fields (serviceName, environment, serviceVersion) are set first; resourceAttributes can override them. Example { 'host.name': 'web-01', 'cloud.region': 'us-east-1' }
serviceName?stringThe service name for metric series. Maps to the OTel resource attribute 'service.name'. Default 'unknown_service'
serviceVersion?stringThe service version for metric series (e.g. '1.2.3'). Maps to the OTel resource attribute 'service.version'.

MetricType

MetricType = "count" | "gauge" | "histogram"

MiddlewareError

  • Error

Properties

PropertyType
output?object
output.statusCode?string | number
status?string | number
status_code?string | number
statusCode?string | number

MultipleSurveyQuestion

MultipleSurveyQuestion = SurveyQuestionBase & object

Type Declaration

NameType
choicesstring[]
hasOpenChoice?boolean
shuffleOptions?boolean
skipSubmitButton?boolean
typetypeof SurveyQuestionType.SingleChoice | typeof SurveyQuestionType.MultipleChoice

NextQuestionBranching

NextQuestionBranching = object

Properties

PropertyType
typetypeof SurveyQuestionBranchingType.NextQuestion

OverrideFeatureFlagsOptions

OverrideFeatureFlagsOptions = false | string[] | Record<string, FeatureFlagValue> | FeatureFlagOverrideOptions

Options for overriding feature flags.

Supports multiple formats:

  • false - Clear all overrides
  • string[] - Enable a list of flags (sets them to true)
  • Record<string, FeatureFlagValue> - Set specific flag values/variants
  • FeatureFlagOverrideOptions - Set both flag values and payloads

PostHogCookieState

PropertyTypeDescription
deviceId?string-
distinctIdstring-
isIdentifiedboolean-
sessionId?string-
sessionLastActivityTimestamp?numberWhen the session last had activity ($sesid[0]), in milliseconds since the Unix epoch.
sessionStartTimestamp?numberWhen the session started ($sesid[2]), in milliseconds since the Unix epoch.

PostHogCoreOptions

PostHogCoreOptions = object

Properties

PropertyTypeDescription
addTracingHeaders?string[]A list of hostnames for which to inject PostHog tracing headers (X-POSTHOG-DISTINCT-ID, X-POSTHOG-SESSION-ID) on outgoing fetch requests. Use this to link requests made from your app to session replays and LLM traces in PostHog. When set, the global fetch is patched on initialization and the headers are added to requests whose hostname matches one of the entries. Hostnames match exactly, so pass hostnames only, without a protocol or path. Requires the SDK to wire up patchFetchForTracingHeaders against this option (currently supported in posthog-react-native).
before_send?BeforeSendFn | BeforeSendFn[]Allows modification or dropping of events before they're sent to PostHog. If an array is provided, the functions are run in order. If a function returns null, the event will be dropped.
bootstrap?objectOption to bootstrap the library with given distinctId and feature flags
bootstrap.distinctId?string-
bootstrap.featureFlagPayloads?Record<string, JsonType>-
bootstrap.featureFlags?Record<string, FeatureFlagValue>-
bootstrap.isIdentifiedId?boolean-
defaultOptIn?booleanIf set to false the SDK will not track until the optIn function is called. Default true
disable_capture_url_hashes?booleanWhether to strip URL fragments (#...) from automatically captured URL fields. Disabled by default for backwards compatibility. Set to true to strip hashes from: - $current_url on automatically captured browser events, including $pageview - $initial_current_url - $session_entry_url - $elements[*].attr__href and $external_click_url for autocapture and dead-click autocapture - Next.js Pages Router $pageview $current_url - web vitals $current_url - logs url.full - conversations current_url and request_url - session replay rrweb meta/custom-event href URLs - heatmap data URLs If your SPA relies on hash-based routes for analytics, enabling this is a breaking behavior change. If you want to capture hashes selectively, leave this as false and use before_send to remove sensitive hash values before events are sent. Default false
disableCompression?booleanWhether to disable GZIP compression Default false
disabled?booleanIf set to true the SDK is essentially disabled (useful for local environments where you don't want to track anything) Default false
disableGeoip?booleanWhether to disable GeoIP lookups Default false
disableRemoteConfig?booleanWhether to load remote config when initialized or not Deprecated Remote config is now always loaded and this option is a no-op. It will be removed in a future version. Default false
disableRemoteFeatureFlags?booleanAdvanced: whether to disable fetching and evaluating feature flags from PostHog entirely. When set to true, reloadFeatureFlags() and the reloads triggered by identify(), group(), setPersonPropertiesForFlags() and reset() become no-ops, and any request to the flags endpoint that still goes out (e.g. to fetch remote config or surveys) carries disable_flags: true so the server skips flag evaluation. Flag values must be supplied via the bootstrap option or updateFlags() instead; getFeatureFlag() and related methods keep working against those values. Until updateFlags() runs, reads return their not-loaded defaults, so use bootstrap for any flags needed at startup. Equivalent to the web SDK's advanced_disable_feature_flags. Note: surveys gated on feature flags will not evaluate unless the survey targeting flags are also provided via updateFlags(). This option cannot be toggled at runtime. posthog-node inherits this option but does not implement it (no-op). Default false
disableSurveys?booleanWhether to load surveys when initialized or not Requires the PostHogSurveyProvider to be used Default false
evaluationContexts?readonly string[]Evaluation contexts for feature flags. When set, only feature flags that have at least one matching evaluation tag will be evaluated for this SDK instance. Feature flags with no evaluation tags will always be evaluated. Examples: ['production', 'web', 'mobile'] Default undefined
evaluationEnvironments?readonly string[]Evaluation environments for feature flags. Deprecated Use evaluationContexts instead. This property will be removed in a future version.
featureFlagsRequestMaxRetries?numberHow many times feature flag requests retry after a transient network error. Set to 0 to disable feature flag request retries. Default 1
featureFlagsRequestTimeoutMs?numberTimeout in milliseconds for feature flag calls Default 10000 for stateful clients, 3000 for stateless
fetchRetryCount?numberHow many times we will retry HTTP requests Default 3
fetchRetryDelay?numberThe delay between HTTP request retries in milliseconds Default 3000
flushAt?numberThe number of events to queue before sending to PostHog (flushing) Default 20
flushInterval?numberThe interval in milliseconds between periodic flushes Default 10000
historicalMigration?booleanSpecial flag to indicate ingested data is for a historical migration Default false
host?stringPostHog API host, usually 'https://us.i.posthog.com' or 'https://eu.i.posthog.com' Default 'https://us.i.posthog.com'
maxBatchSize?numberThe maximum number of queued messages to be flushed as part of a single batch (must be higher than flushAt) Default 100
maxQueueSize?numberThe maximum number of cached messages either in memory or on the local storage (must be higher than flushAt) When the queue is full, the SDK drops the oldest event first. Default 1000
personProfiles?"always" | "identified_only" | "never"Determines when to create Person Profiles for users. - 'always': Always create a person profile for every user (anonymous and identified). - 'identified_only': Only create a person profile when the user is identified via identify(), alias(), or group(). Events captured before identification will NOT have person profiles and will be anonymous events. - 'never': Never create person profiles. identify(), alias(), and group() will be no-ops. Default 'identified_only' Examples // Only create profiles when users are identified (recommended for most apps) const posthog = new PostHog('<api_key>', { personProfiles: 'identified_only', }) // Later when user logs in: posthog.identify('user-123', { email: 'user@example.com' }) // Always create profiles (for apps where you want to track all users) const posthog = new PostHog('<api_key>', { personProfiles: 'always', }) // Never create profiles (anonymous analytics only) const posthog = new PostHog('<api_key>', { personProfiles: 'never', })
preloadFeatureFlags?booleanWhether to load feature flags when initialized or not Default true
remoteConfigRequestTimeoutMs?numberTimeout in milliseconds for remote config calls Default 3000
requestTimeout?numberTimeout in milliseconds for any calls Default 10000
sendFeatureFlagEvent?booleanWhether to track that getFeatureFlag was called (used by Experiments) In posthog-node this is also the default for reads from an evaluateFlags() snapshot (isEnabled() / getFlag()). Pass sendFeatureFlagEvents to one of those reads, or to a single-flag getter, to override it for that call. Default true
sessionExpirationTimeSeconds?numberFor Session Analysis how long before we expire a session in seconds Default 1800

PostHogEventProperties

PostHogEventProperties = object

Index Signature

[key: string]: JsonType

PostHogFeatureFlag

PostHogFeatureFlag = object

Properties

PropertyTypeDescription
activeboolean-
bucketing_identifier?FeatureFlagBucketingIdentifier-
deletedboolean-
ensure_experience_continuityboolean-
evaluation_contexts?string[]Evaluation context tags set on the flag. The local evaluation poller keeps a flag only when this list is empty or shares at least one entry with the SDK's evaluationContexts. Absent when the server does not report it.
evaluation_runtime?FeatureFlagEvaluationRuntime | nullWhere the flag is meant to be evaluated. Absent or null on a flag that does not set a runtime, and on servers older than the field; both mean all, the default PostHog applies.
evaluation_tags?string[]Legacy name for evaluation_contexts. Servers older than the field rename (PostHog, 2026-03-11) expose the same list under this key on /flags/definitions. Read as a fallback so local-evaluation context filtering still works against those servers.
experiment_setnumber[]-
filters?object-
filters.aggregation_group_type_index?number-
filters.early_exit?boolean-
filters.feature_enrollment?boolean | nullEarly-access feature flag. The person's opt-in, stored in the person property $feature_enrollment/<flag key>, decides the flag before holdouts and release conditions.
filters.groups?FeatureFlagCondition[]-
filters.holdout?{ exclusion_percentage: number; id: number; } | null-
filters.multivariate?object-
filters.multivariate.variantsobject[]-
filters.payloads?Record<string, string>-
has_experiment?booleanWhether the flag is linked to an experiment. Absent when the server does not report it.
idnumber-
keystring-
namestring-
rollout_percentagenull | number-

PostHogFetchBodyBytes

PostHogFetchBodyBytes = Uint8Array & object

Type Declaration

NameType
bufferArrayBuffer

PostHogFetchOptions

PostHogFetchOptions = object

Extended by

  • EmailFetchOptions

Properties

PropertyType
body?string | Blob | PostHogFetchBodyBytes
credentials?"omit"
headersobject
method"GET" | "POST" | "PUT" | "PATCH"
mode?"no-cors"
redirect?"follow" | "manual" | "error"
signal?AbortSignal

PostHogFetchResponse

PostHogFetchResponse = object

Properties

PropertyType
body?ReadableStream<Uint8Array> | null
headers?object
headers.get(name) => string | null
json() => Promise<any>
statusnumber
text() => Promise<string>

PostHogFlagsResponse

PostHogFlagsResponse = Omit<PostHogRemoteConfig, "hasFeatureFlags"> & object

Type Declaration

NameTypeDescription
errorsWhileComputingFlagsboolean-
evaluatedAt?number-
featureFlagPayloadsobject-
featureFlagsobject-
flagsobject-
minimalFlagCalledEvents?booleanServer-controlled gate for minimal $feature_flag_called events. true only when the project opted in; omitted otherwise. Absence always means full events.
quotaLimited?string[]-
requestId?string-
sessionRecording?boolean | {[key: string]: JsonType; }-

PostHogForRequests

PostHogForRequests = Pick<PostHogBackendClient, "withContext" | "withSpan" | "getContext" | "metrics" | "apiKey" | "options" | "_flushMetricsWithinInvocation">

PostHogInterceptorOptions

PropertyTypeDescription
captureExceptions?boolean | ExceptionCaptureOptionsEnable exception capture. Pass true for defaults or an object to configure. Default false
getDistinctId?(request) => string | undefinedReturns the distinct ID for a request, such as the signed-in user's ID from your auth layer. It takes precedence over the X-POSTHOG-DISTINCT-ID tracing header and over a distinct ID already set in the PostHog context. Return undefined to fall back to those.

PostHogLogsConfig

Configuration for the logs feature on new PostHog(key, { logs: ... }). All fields are optional; per-SDK defaults apply (mobile vs browser tune differently for cellular cost vs tab-suspension behavior).

Properties

PropertyTypeDescription
beforeSend?BeforeSendLogFn | BeforeSendLogFn[]Pre-send filter. See BeforeSendLogFn for shape and examples. Configure as a single function or a chain.
environment?stringDeployment environment attached as OTLP deployment.environment (e.g. 'production', 'staging', 'dev').
flushIntervalMs?numberHow often the periodic background flush fires (ms). Records also flush eagerly when the buffer fills, on AppState changes (RN), and on shutdown(). Lower values trade battery/bandwidth for fresher data. Default: 10000 (RN) / 3000 (browser).
maxBatchRecordsPerPost?numberMax records per outbound POST. Keeps each request under the server's request body cap. On a 413 response, the SDK halves this value, retries the same records, then ramps back up by 1 per healthy send. A 413 on a single-record batch drops the record (it's larger than the server can accept regardless of batch size). Default: 50 (RN) / 100 (browser).
maxBufferSize?numberNumber of buffered records that triggers an immediate flush. Records also flush on the periodic interval and on shutdown(). The queue can grow past this while an async flush is in flight (e.g. during a synchronous burst); a separate, larger memory backstop evicts the oldest only once the queue exceeds the per-interval rate cap. Default: 100.
rateCap?objectTumbling-window rate cap. Bounds how many records can be captured within a sliding (technically tumbling) time window. Records exceeding the cap are dropped synchronously at captureLog() (they never enter the buffer or consume bandwidth). A single warn line is logged per window when the cap is hit. Defaults are per-SDK; on RN the default is { maxLogs: 500, windowMs: 10000 } (≈50 logs/sec ceiling, tuned for cellular bandwidth). Examples Allow brief bursts up to 1000/min logs: { rateCap: { maxLogs: 1000, windowMs: 60000 } } Disable the cap entirely (unbounded) logs: { rateCap: { maxLogs: undefined } }
rateCap.maxLogs?numberMax records accepted per windowMs window. undefined = unbounded.
rateCap.windowMs?numberWindow length in ms. Tumbling, not sliding — the counter resets the first time a capture fires after the window expires.
resourceAttributes?Record<string, LogAttributeValue>Extra OTLP resource attributes attached to every record. Spread first; SDK-controlled keys (service.name, telemetry.sdk.*, RN's os.*) are layered on top so users cannot accidentally clobber them. Use the dedicated serviceName / environment / serviceVersion fields to override those keys.
serviceName?stringService name attached to every record as the OTLP service.name resource attribute. Used by the Logs UI for filtering / grouping. Defaults to 'unknown_service' when unset.
serviceVersion?stringService version attached as OTLP service.version. Useful for correlating regressions to specific app releases.

PostHogOptions

PostHogOptions = Omit<PostHogCoreOptions, "before_send" | "disable_capture_url_hashes" | "disableGeoip" | "flushInterval" | "maxQueueSize" | "fetchRetryCount" | "fetchRetryDelay" | "disableCompression" | "requestTimeout"> & object & ExceptionRateLimiterConfig

Type Declaration

NameTypeDescription
__preview_capture_bot_pageviews?booleanDeprecated Use __previewCaptureBotPageviews instead. This property will be removed in the next major version.
__previewCaptureBotPageviews?booleanPREVIEW - MAY CHANGE WITHOUT WARNING - DO NOT USE IN PRODUCTION Enables collection of bot traffic as $bot_pageview events instead of dropping them. When enabled, events with a $raw_user_agent property that matches the bot detection list will have their $pageview event renamed to $bot_pageview. To use this feature, pass the user agent in event properties: client.capture({ distinctId: 'user_123', event: '$pageview', properties: { $raw_user_agent: req.headers['user-agent'] } })
appHost?stringYour PostHog app host, such as https://posthog.example.com. emails.send sends there. Needed only when host is not PostHog Cloud, for example a reverse proxy, which must not receive the secret key. On PostHog Cloud, the client derives https://us.posthog.com or https://eu.posthog.com from host. When host is not PostHog Cloud and appHost is not set, every posthog.emails call fails with missing_app_host and sends nothing. A self-hosted PostHog needs a version from 2026-11-18 or later, and an older one answers email calls with a 404. With enableLocalEvaluation on, the client polls flag definitions from host with secretKey, and getRemoteConfigPayload() always sends secretKey to host. When host is a proxy that must not see the key, set enableLocalEvaluation: false and don't call getRemoteConfigPayload() on this client.
before_send?BeforeSendFn | BeforeSendFn[]Deprecated Use beforeSend instead. This property will be removed in the next major version.
beforeSend?BeforeSendFn | BeforeSendFn[]Allows modification or dropping of events before they're sent to PostHog. If an array is provided, the functions are run in order. If a function returns null, the event will be dropped. Remarks The hook gets a copy of the finished event: the event's own values, then the values filled from context, register() and registerOptions(), then the values the SDK adds (such as $is_server, $geoip_disable, feature flag properties and options.process_person_profile). It has the final say: it can change or remove any of them, and nothing is added after it. Set $geoip_disable in properties to change GeoIP; the disableGeoip and groups fields are already applied to the properties it sees. On $identify, $create_alias, $merge_dangerously, $groupidentify, $set and $set_once events it sees options.process_person_profile and no $process_person_profile property. Those events get their default from the event name the call used, so a hook that renames an event to one of them must set options.process_person_profile itself.
captureAiCompression?"none" | "gzip" | "deflate" | "zstd"How captureAi requests compress their body, with the same values as captureCompression. It does not read captureCompression or disableCompression. Default 'gzip'
captureAiMaxQueueSize?numberThe maximum number of captureAi events held in memory waiting to be sent. When the queue is full, the oldest AI event is dropped and reported through the 'error' event. Default 1000
captureAiRequestTimeoutMs?numberTimeout in milliseconds for each captureAi request. Analytics capture requests use requestTimeout. Default 30000
captureCompression?"none" | "gzip" | "deflate" | "zstd"How analytics capture requests compress their body. 'deflate' is zlib-wrapped. 'zstd' needs Node 22.15 or later and falls back to 'gzip' elsewhere, including the edge build. When not set, disableCompression: true means 'none'. Default 'gzip'
captureMaxRetries?numberHow many times a capture request is retried after its first attempt, on both capture lanes. Waits start at 100 ms and double each retry, with jitter, up to 30 seconds; a Retry-After header can raise a wait. Only HTTP 404, 408, 429, 500, 502, 503 and 504 and network errors are retried. When not set, fetchRetryCount is used. Default 3
captureTracingHeaders?booleanWhether the Express, NestJS, Hono, and instrumentRequest integrations read the X-POSTHOG-DISTINCT-ID and X-POSTHOG-SESSION-ID request headers into the request context. A distinct id or session id you pass explicitly always wins over these headers, and they are never used for authentication. Turning it off does not turn off readPostHogCookie. To stop all request linking, set captureTracingHeaders: false and leave readPostHogCookie off (its default). Default true
custom_blocked_useragents?string[]Deprecated Use customBlockedUserAgents instead. This property will be removed in the next major version.
customBlockedUserAgents?string[]Additional user agent strings to block from being tracked. These are combined with the default list of blocked user agents. Default []
disable_capture_url_hashes?booleanDeprecated Use disableCaptureUrlHashes instead. This property will be removed in the next major version.
disableCaptureUrlHashes?booleanWhether to strip URL fragments (#...) from automatically captured request URLs. Default false
disableCompression?booleanWhether to disable GZIP compression. Analytics capture requests use captureCompression when it is set, and captureAi requests use captureAiCompression. Default false
disableGeoip?booleanWhether to disable GeoIP lookups for events and feature flag requests. When true, every event gets $geoip_disable: true unless the event, its context, or register() sets $geoip_disable. Pass disableGeoip: false (here or per call) and set $ip in event properties to geolocate from a client IP. Setting $ip alone still skips GeoIP while disableGeoip is true. Default true
emailRequestMaxRetries?numberNumber of retries for a posthog.emails call after a network error, a rate limit, or an unavailable service. Every retry of a send carries the same idempotency key. Set to 0 when a job runner already retries the send. A send's own maxRetries overrides it. Default 2
emailRequestTimeoutMs?numberTimeout in milliseconds for each posthog.emails request: a send, a status read, a preferences change, or one attachment upload. Raise it when large files upload slowly. Rendering a react element has the same limit. Default 15000
enableExceptionAutocapture?booleanAttach process uncaughtException and unhandledRejection listeners to capture unhandled errors automatically. Default false
enableFullAiCapture?booleanCapture full AI content: PostHog AI wrapper events route through the dedicated AI capture endpoint, skip string truncation, and pass media (base64 / data URIs) through unredacted. Privacy mode always wins. Defaults to false.
enableLocalEvaluation?booleanWhether to poll feature flag definitions for local evaluation when secretKey, personalApiKey, or flagDefinitionCacheProvider is set. Set to false when secretKey is only for getRemoteConfigPayload() or emails. Default true
evaluationContexts?readonly string[]Evaluation contexts for feature flags. When set, only feature flags that have at least one matching evaluation tag will be evaluated for this SDK instance. Feature flags with no evaluation tags will always be evaluated. Examples: ['production', 'backend', 'api'] Default undefined
evaluationEnvironments?readonly string[]Evaluation environments for feature flags. Deprecated Use evaluationContexts instead. This property will be removed in a future version.
featureFlagsLogWarnings?booleanControls whether FeatureFlagEvaluations filter helpers (onlyAccessed() and only()) log warnings when their input is unexpected — for example, calling onlyAccessed() before accessing any flags, or passing unknown keys to only(). Default true
featureFlagsPollingInterval?number | nullThe interval in milliseconds between polls for refreshing feature flag definitions. Defaults to 30 seconds. The minimum is 100 ms, and a lower value is raised to it. Set to null to disable automatic polling. Definitions are still loaded on initialization; call reloadFeatureFlags() to refresh them manually. Until refreshed, local evaluation uses the last loaded definitions.
fetch()?(url, options) => Promise<PostHogFetchResponse>Custom HTTP transport replacing global fetch. Capture requests pass redirect: 'manual' and follow up to 5 same-origin 307 or 308 redirects, and a custom fetch that follows redirects itself still works.
fetchRetryCount?numberHow many times HTTP requests are retried. Capture requests use captureMaxRetries when it is set. Default 3
fetchRetryDelay?numberThe delay between HTTP request retries in milliseconds. Capture requests do not use it: see captureMaxRetries for their retry waits. Default 3000
flagDefinitionCacheProvider?FlagDefinitionCacheProvider<FlagDefinitionCacheInput>Optional cache provider for feature flag definitions. Allows custom caching strategies (Redis, database, etc.) for flag definitions in multi-worker environments. If not provided, defaults to in-memory cache. Without a secretKey or personalApiKey, this instance only reads cached definitions on each refresh; it does not call shouldFetchFlagDefinitions or publish definitions. With a credential, it uses the provider's fetch decision to coordinate fetching fresh definitions from PostHog and publishing them to the cache. This enables distributed coordination where only one worker fetches flags while others use cached data, reducing API calls and improving performance. Example import type { FlagDefinitionCacheProvider } from 'posthog-node' class RedisCacheProvider implements FlagDefinitionCacheProvider { // ... implementation } const client = new PostHog('api-key', { flagDefinitionCacheProvider: new RedisCacheProvider(redis) })
flushInterval?numberThe interval in milliseconds between periodic flushes Default 5000
isServer?booleanWhether to attach the $is_server: true property to every captured event. Remarks Defaults to true because this SDK is intended for server-side use, where the property lets PostHog distinguish server events from browser and react-native events. Set this to false when running the SDK as a client/CLI so the event is attributed to the device OS normally instead of being marked as a server event. When false, the $is_server property is omitted entirely. A $is_server value set on the event, in context or with register() wins over this setting. Default true Example // CLI usage: don't mark events as server-side new PostHog('key', { isServer: false })
logs?PostHogLogsConfigConfiguration for the posthog.logger / posthog.captureLog logs API. Logs are sent to PostHog Logs as OTLP records, with no OpenTelemetry packages needed. Each record carries the active span's trace_id / span_id and, inside withContext, the distinctId and sessionId, so logs join back to traces, persons and replays. serviceName defaults to the traces / metrics serviceName. Example const client = new PostHog('phc_...', { logs: { serviceName: 'checkout-api' } }) client.logger.info('order placed', { order_id: 'ord_1' })
maxCacheSize?numberMaximum number of distinct ids held in the cache that deduplicates $feature_flag_called calls per user. When the cache is full the least recently used distinct ids are evicted. Defaults to 50000.
maxQueueSize?numberThe maximum number of analytics events held in memory waiting to be sent (must be higher than flushAt). When the queue is full, the oldest event is dropped and reported through the 'error' event. captureAi events have their own queue, sized by captureAiMaxQueueSize, and do not count toward this limit. Default 10000
metrics?MetricsConfigConfiguration for the posthog.metrics API (count, gauge, histogram). Set serviceName so series can be filtered per service in the Metrics UI. Example const client = new PostHog('phc_...', { metrics: { serviceName: 'billing-worker' } }) client.metrics.count('invoices.processed')
migratedFrom?stringThe provider your email moved from, such as 'resend'. Sent with every posthog.emails request.
persistence?"memory"Storage backend for client opt-out state and super properties. Node holds state in memory only, so it resets on restart.
personalApiKey?stringDeprecated Use secretKey instead.
privacyMode?booleanRedact prompts, outputs and error details from every event that the PostHog AI integrations (@posthog/ai) capture with this client. Per-call privacy settings can only add redaction. Defaults to false.
reactEmailRenderer?EmailReactRendererRenders the react element of an emails.send. Set it when you bundle your app, such as for Cloudflare Workers, Convex, or Vercel Edge: posthog-node doesn't bundle @react-email/render, so apps that never send react don't carry it. Without it, posthog-node loads @react-email/render from node_modules when a send has react. Needs posthog-node 6.2.0 or later. Example const client = new PostHog('phc_...', { reactEmailRenderer: await import('@react-email/render') })
readPostHogCookie?boolean | { optOutCapturingByDefault?: boolean; sessionIdleTimeoutSeconds?: number; }Lets the Express, NestJS, Hono and instrumentRequest integrations read the session ID, and the distinct ID of an identified user, from the posthog-js cookie when a request has neither tracing header. createReactRouterErrorHandler also reads an anonymous visitor's distinct ID, and sends their exceptions personless. Turn it on only when posthog-js stores opt-out consent in a cookie, or when you do not use opt-out: the server cannot read an opt-out that posthog-js keeps in localStorage (its default). It needs cookie-backed posthog-js persistence (the default localStorage+cookie, or cookie), the default cookie name (no persistence_name), and the default __ph_opt_in_out_<token> consent cookie name. Set sessionIdleTimeoutSeconds when posthog-js uses a custom session_idle_timeout_seconds, and set optOutCapturingByDefault when posthog-js uses opt_out_capturing_by_default, so a visitor with no consent cookie counts as opted out. A request sent right after identify() or reset() can still carry the previous identity, because posthog-js saves the cookie with a short delay. When captureTracingHeaders is false, the tracing headers are ignored and every request falls back to the cookie. To stop all request linking, also leave this option off. Default false
requestTimeout?numberTimeout in milliseconds for any calls. captureAi requests use captureAiRequestTimeoutMs. Default 10000
secretKey?stringCredential for fetching local feature flag definitions, decrypting remote config and sending email. Accepts either a Personal API Key (phx_...) or a Project Secret API Key (phs_...). Local evaluation can also use definitions from flagDefinitionCacheProvider without this credential. Remote config payload decryption via getRemoteConfigPayload still requires it. emails.send needs a Project Secret API Key with the transactional_email:write scope; set enableLocalEvaluation: false when the key is only for email. Prefer this over the deprecated personalApiKey option; when both are set, secretKey takes precedence. Example const client = new PostHog('phc_...', { secretKey: 'phs_...' })
strictLocalEvaluation?booleanWhen enabled, all feature flag evaluations will use local evaluation only, never falling back to server-side evaluation. This prevents unexpected server requests and associated costs when using local evaluation. Flags that cannot be evaluated locally (e.g., those with experience continuity) will return undefined instead of making a server request. Default false
traces?TracesConfigExperimental Configuration for distributed tracing (startSpan / withSpan). Tracing is off until this is set; supplying it is all that's needed to turn it on. Set serviceName so spans can be attributed and grouped per service — the product aggregates operations by service and span name. shutdown() drains spans that have already ended, within the shutdown timeout; spans still open at that point are discarded. Example const client = new PostHog('phc_...', { traces: { serviceName: 'checkout-api' } }) await client.withSpan('charge', () => stripe.charge(order)) Subject to change in a minor release.
waitUntil()?(promise) => voidExperimental Provides the API to extend the lifetime of a serverless invocation until background work (like flushing analytics events) completes after the response is sent. Subject to change in a minor release. Example // Vercel import { waitUntil } from '@vercel/functions' new PostHog('key', { waitUntil })
waitUntilDebounceMs?numberExperimental Debounce interval in milliseconds for the waitUntil-based flush. After the last event is enqueued, the SDK waits this long before flushing. Subject to change in a minor release. Default 50
waitUntilMaxWaitMs?numberExperimental Maximum time in milliseconds to debounce before forcing a flush. Prevents starvation from rapid concurrent captures. Subject to change in a minor release. Default 500

PostHogRemoteConfig

PostHogRemoteConfig = object

Properties

PropertyTypeDescription
capturePerformance?boolean | {[key: string]: JsonType; }Capture performance remote config. Either a boolean (false = disabled) or a map with configuration. When a map, network_timing (boolean) controls whether network timing capture is enabled remotely.
errorTracking?boolean | {[key: string]: JsonType; }Error tracking remote config. Either a boolean (false = disabled) or a map with configuration. When a map, autocaptureExceptions (boolean) controls whether automatic exception capture is enabled remotely.
hasFeatureFlags?booleanIndicates if the team has any flags enabled (if not we don't need to load them)
logs?boolean | {[key: string]: JsonType; }Logs feature remote config. When a map, captureConsoleLogs (boolean) is the local opt-in flag for console.* autocapture (read by the JS SDK's PostHogLogs extension to decide whether to load the autocapture bundle).
sessionRecording?boolean | {[key: string]: JsonType; }-
supportedCompression?Compression[]Supported compression algorithms
surveys?boolean | Survey[]Whether surveys are enabled

PreparedEventMessage

PreparedEventMessage = object

An event as prepareEventMessage() builds it: the shape of EventMessage, with the distinct id resolved and the properties and options filled from every layer, after beforeSend.

Properties

PropertyTypeDescription
disableGeoip?booleanPer-call disableGeoip flag, if provided.
distinctIdstringResolved distinct ID after checking the call, withContext(), and personless fallback.
eventstringFinal event name after SDK normalization (such as $bot_pageview preview renames).
options?EventOptionsThe event's options, sent to capture unchanged.
propertiesPostHogEventPropertiesMerged event properties after context, register(), SDK defaults, and beforeSend.
timestamp?DateExplicit event timestamp, if provided or set by beforeSend.
uuid?stringCanonical event UUID.

Properties

Properties = Record<string, Property>

Property

Property = any

Common types shared across PostHog SDKs

PropertyFilters

PropertyFilters = Record<string, { operator: PropertyOperator; values: string[]; }>

PropertyGroup

PropertyGroup = object

Properties

PropertyType
type"AND" | "OR"
valuesPropertyGroup[] | FlagProperty[]

PropertyMatchType

PropertyMatchType = SurveyMatchType

PropertyOperator

PropertyOperator = PropertyMatchType | "gt" | "lt"

RatingSurveyQuestion

RatingSurveyQuestion = SurveyQuestionBase & object

Type Declaration

NameType
displaySurveyRatingDisplay
lowerBoundLabelstring
scale2 | 3 | 5 | 7 | 10
skipSubmitButton?boolean
typetypeof SurveyQuestionType.Rating
upperBoundLabelstring

ReactRouterErrorArgs

The part of React Router's handleError arguments the handler reads, so react-router is not a dependency.

Properties

PropertyType
requestRequest

ReactRouterErrorHandlerOptions

Type ParameterDefault type
A extends ReactRouterErrorArgsReactRouterErrorArgs

Properties

PropertyTypeDescription
handleError?(error, args) => voidYour own handleError, called for every error after the capture decision, captured or not. Exporting handleError replaces React Router's own logging; without this option the handler logs the way React Router does (console.error, skipping aborted requests).
shouldCapture?(error, args) => booleanReturn false to skip capturing an error the handler would otherwise capture. It receives the error to capture: for a data(error, init) a middleware threw, the error inside.

ResponseBasedBranching

ResponseBasedBranching = object

Properties

PropertyType
responseValuesRecord<string, any>
typetypeof SurveyQuestionBranchingType.ResponseBased

SendFeatureFlagsOptions

SendFeatureFlagsOptions = object

Properties

PropertyTypeDescription
flagKeys?string[]Restrict evaluation to these flag keys.
groupProperties?Record<string, Properties>Group properties keyed by group type for evaluating group-targeted flags.
groupPropertyKeysKnownAbsent?Record<string, string[]>Group property keys you know each group doesn't have, by group type name. A key applies only to its own group type. Otherwise follows personPropertyKeysKnownAbsent, with the 1000-key limit applying to each group type's list.
onlyEvaluateLocally?booleanSkip remote /flags fallback and evaluate only against locally loaded flag definitions.
personProperties?PropertiesPerson properties used during flag evaluation instead of stored server properties.
personPropertyKeysKnownAbsent?string[]Person property keys you know this person doesn't have. Local evaluation treats a listed key as absent even when personProperties has a value for it, so is_not_set and the negated operators match and every other supported operator doesn't, without a /flags request. A filter with an operator the SDK can't evaluate locally, or with an operator that needs a value but has none, still falls back to /flags. The list is sent to /flags when evaluation falls back to it. At most 1000 keys, counting duplicates; with a longer list no flags are evaluated and the event is sent without flag properties.

SentryIntegrationOptions

SentryIntegrationOptions = object

Properties

PropertyType
organization?string
prefix?string
projectId?number
sendExceptionsToPostHog?boolean
severityAllowList?SeverityLevel[] | "*"

SetPersonPropertiesMessage

SetPersonPropertiesMessage = object

Properties

PropertyTypeDescription
distinctIdstringUser distinct ID. Falls back to withContext() when missing or blank.
options?EventOptionsProcessing options sent with this event to capture v1.
properties?Record<string | number, any>Person properties to overwrite ($set).
propertiesOnce?Record<string | number, any>Person properties to write only when unset ($set_once).

SeverityLevel

SeverityLevel = typeof severityLevels[number]

Span

Experimental

A handle to a span in progress.

Every method is safe to call at any time, including after end() and on no-op handles, so calling code never has to branch on whether tracing is on.

Subject to change in a minor release.

Properties

PropertyModifierTypeDescription
spanIdreadonlystring | nullExperimental This span's 16-hex-char span id. null when traceparent() is null.
traceIdreadonlystring | nullExperimental This span's 32-hex-char trace id, for correlating logs from other loggers (pino, winston) with the trace. null when there is no id to report: the same cases where traceparent() returns null.

Methods

addEvent()

addEvent(name, attributes?, timestamp?): this

Experimental

Record a timestamped event within the span, e.g. a cache miss or a retry. Defaults to the current time.

One event carries at most 128 attributes; further keys are dropped and counted on the exported event. Use maxEventsPerSpan to bound how many events a span carries.

Parameters
ParameterType
namestring
attributes?SpanAttributes
timestamp?SpanTimeInput
Returns

this

end()

end(endTime?): void

Experimental

End the span and queue it for export. Idempotent — later calls no-op.

Parameters
ParameterTypeDescription
endTime?SpanTimeInputOverride the recorded end. Invalid values fall back to the derived end time; an end before the start is corrected to the start.
Returns

void

recordException()

recordException(error): this

Experimental

Record an exception on the span: sets status error and attaches an exception event carrying exception.type, exception.message and, where the thrown value has one, exception.stacktrace. The stack is truncated to maxAttributeValueLength like any other attribute value, and beforeSpanSend sees it before it is exported. Does not end the span.

Parameters
ParameterType
errorunknown
Returns

this

setAttribute()

setAttribute(key, value): this

Experimental

Set a single attribute. Ignored after end().

Parameters
ParameterType
keystring
valueSpanAttributeValue
Returns

this

setAttributes()

setAttributes(attributes): this

Experimental

Merge several attributes at once. Ignored after end().

Parameters
ParameterType
attributesSpanAttributes
Returns

this

setStatus()

setStatus(status, message?): this

Experimental

Set the span's outcome. Last write wins.

When a withSpan callback throws, the SDK sets error automatically — unless the callback already set ok, which is treated as final.

Parameters
ParameterType
statusSpanStatusCode
message?string
Returns

this

traceparent()

traceparent(): string | null

Experimental

This span's W3C traceparent header value (00-<traceId>-<spanId>-<flags>), for propagating the trace to another service. A span continuing a remote trace propagates the flags byte it was handed, so a downstream sampler sees the decision the head sampler made; a trace started here is sampled.

When tracing is off, a span started with a parent header echoes that header back — version and sampled flag included — so a service that records nothing still keeps a distributed trace whole. With no parent there is no context to carry and this returns null, so an id this SDK never recorded cannot propagate.

Returns

string | null

tracestate()

tracestate(): string | null

Experimental

This span's W3C tracestate value, or null when it has none.

Returns

string | null

updateName()

updateName(name): this

Experimental

Replace the span's name. Useful when the low-cardinality name is only known after work begins — a route template resolving mid-request, say.

Span names should be low-cardinality operation names (GET /users/:id), never interpolated with ids: PostHog aggregates operations by service and name, so variable values belong in attributes.

Parameters
ParameterType
namestring
Returns

this

SpanAttributes

SpanAttributes = Record<string, SpanAttributeValue>

SpanAttributeValue

SpanAttributeValue = string | number | boolean | bigint | SpanAttributeValue[] | {[key: string]: SpanAttributeValue; } | null | undefined

Experimental

A value that can be attached to a span, span event, or resource.

The ingestion service flattens attribute values to strings for storage, so primitives are strongly preferred — nested arrays and objects survive only as serialized strings and cannot be filtered on. null and undefined drop the key.

Subject to change in a minor release.

SpanKind

SpanKind = "internal" | "server" | "client" | "producer" | "consumer"

Experimental

What kind of work a span represents. Mirrors the OpenTelemetry span kinds.

Default

TypeScript
'internal'
@experimental Subject to change in a minor release.

SpanRecord

Experimental

A completed span as beforeSpanSend sees it: plain values, not the OTLP wire encoding — userId: 42 reads as 42, not { intValue: "42" }.

Subject to change in a minor release.

Properties

PropertyModifierTypeDescription
attributespublicSpanAttributesExperimental Editable in place; this is where to redact.
endTimepublicnumberExperimental Millisecond epoch.
eventspublicobject[]Experimental
kindpublicSpanKindExperimental
namepublicstringExperimental
parentSpanId?readonlystringExperimental Absent on a root span.
spanIdreadonlystringExperimental
startTimepublicnumberExperimental Millisecond epoch.
status?publicobjectExperimental
status.codepublicSpanStatusCode-
status.message?publicstring-
traceIdreadonlystringExperimental Assignment to any of the three identity fields is ignored with a debug warning: rewriting ids orphans children that already shipped.

SpanStatusCode

SpanStatusCode = "ok" | "error"

Experimental

Outcome of the operation a span covers. A span that never has a status set is exported as unset, which is not the same as ok.

Subject to change in a minor release.

SpanTimeInput

SpanTimeInput = number | Date

Experimental

A point in time, as a millisecond epoch number or a Date.

Subject to change in a minor release.

SpecificQuestionBranching

SpecificQuestionBranching = object

Properties

PropertyType
indexnumber
typetypeof SurveyQuestionBranchingType.SpecificQuestion

StartSpanOptions

Experimental

Options accepted by startSpan and withSpan.

Subject to change in a minor release.

Properties

PropertyTypeDescription
attributes?SpanAttributesExperimental Attributes to set at span start. User-supplied keys win over the SDK's auto-attached context attributes.
kind?SpanKindExperimental What kind of work the span represents. Default 'internal'
parent?string | SpanExperimental Parent of this span: either a span handle, or a raw W3C traceparent string to continue a trace started by another service. When omitted the parent is the currently active span, or none. Only handles returned by this SDK are honoured; any other Span yields an inert span. Example Continue an inbound trace posthog.withSpan('POST /checkout', { parent: req.get('traceparent') }, handler)
startTime?SpanTimeInputExperimental Backdate the span's start. Values outside the representable range fall back to the current time; starts more than 24 hours old are warned about, because the server clamps them to receive time.
tracestate?stringExperimental The W3C tracestate value accompanying a traceparent-string parent. Ignored when parent is a span handle — those inherit the parent's tracestate. Preserved opaquely and passed on to children.

Survey

Survey = object

Properties

PropertyType
appearance?SurveyAppearance
conditions?object
conditions.actions?object
conditions.actions.valuesSurveyActionType[]
conditions.deviceTypes?string[]
conditions.deviceTypesMatchType?SurveyMatchType
conditions.events?object
conditions.events.repeatedActivation?boolean
conditions.events.values?SurveyEventWithFilters[]
conditions.linkedFlagVariant?string
conditions.seenSurveyWaitPeriodInDays?number
conditions.selector?string
conditions.url?string
conditions.urlMatchType?SurveyMatchType
current_iteration?number | null
current_iteration_start_date?string | null
description?string
enable_partial_responses?boolean | null
end_date?string
feature_flag_keys?object[]
idstring
internal_targeting_flag_key?string
linked_flag_key?string
namestring
questionsSurveyQuestion[]
schedule?SurveySchedule | null
start_date?string
targeting_flag_key?string
translations?Record<string, SurveyTranslation>
typeSurveyType

SurveyActionType

SurveyActionType = object

Properties

PropertyType
idnumber
name?string
steps?ActionStepType[]

SurveyAppearance

SurveyAppearance = object

Properties

PropertyType
allowGoBack?boolean
autoDisappear?boolean
backButtonText?string
backgroundColor?string
borderColor?string
displayIntroScreen?boolean
displayThankYouMessage?boolean
fontFamily?string
inputBackground?string
inputTextColor?string
introScreenButtonText?string
introScreenDescription?string
introScreenDescriptionContentType?SurveyQuestionDescriptionContentType
introScreenHeader?string
placeholder?string
position?SurveyPosition
ratingButtonActiveColor?string
ratingButtonColor?string
shuffleQuestions?boolean
submitButtonColor?string
submitButtonText?string
submitButtonTextColor?string
surveyPopupDelaySeconds?number
textColor?string
thankYouMessageCloseButtonText?string
thankYouMessageDescription?string
thankYouMessageDescriptionContentType?SurveyQuestionDescriptionContentType
thankYouMessageHeader?string
widgetColor?string
widgetLabel?string
widgetSelector?string
widgetType?SurveyWidgetType

SurveyEventWithFilters

PropertyType
namestring
propertyFilters?PropertyFilters

SurveyMatchType

SurveyMatchType = typeof SurveyMatchType[keyof typeof SurveyMatchType]

SurveyPosition

SurveyPosition = typeof SurveyPosition[keyof typeof SurveyPosition]

SurveyQuestion

SurveyQuestion = BasicSurveyQuestion | LinkSurveyQuestion | RatingSurveyQuestion | MultipleSurveyQuestion

SurveyQuestionBase

SurveyQuestionBase = object

Properties

PropertyType
branching?NextQuestionBranching | EndBranching | ResponseBasedBranching | SpecificQuestionBranching
buttonText?string
description?string | null
descriptionContentType?SurveyQuestionDescriptionContentType
idstring
optional?boolean
originalQuestionIndexnumber
questionstring
translations?Record<string, SurveyQuestionTranslation>
validation?SurveyValidationRule[]

SurveyQuestionDescriptionContentType

SurveyQuestionDescriptionContentType = typeof SurveyQuestionDescriptionContentType[keyof typeof SurveyQuestionDescriptionContentType]

SurveyQuestionTranslation

PropertyType
buttonText?string
choices?string[]
description?string | null
link?string | null
lowerBoundLabel?string
question?string
upperBoundLabel?string

SurveyRatingDisplay

SurveyRatingDisplay = typeof SurveyRatingDisplay[keyof typeof SurveyRatingDisplay]

SurveySchedule

SurveySchedule = typeof SurveySchedule[keyof typeof SurveySchedule]

SurveyTranslation

PropertyType
backButtonText?string
introScreenButtonText?string
introScreenDescription?string
introScreenHeader?string
name?string
submitButtonText?string
thankYouMessageCloseButtonText?string
thankYouMessageDescription?string
thankYouMessageHeader?string

SurveyType

SurveyType = typeof SurveyType[keyof typeof SurveyType]

SurveyValidationRule

PropertyType
errorMessage?string
typeSurveyValidationType
value?number

SurveyValidationType

SurveyValidationType = typeof SurveyValidationType[keyof typeof SurveyValidationType]

SurveyWidgetType

SurveyWidgetType = typeof SurveyWidgetType[keyof typeof SurveyWidgetType]

TracesConfig

Experimental

Configuration for distributed tracing, passed as the traces client option. Tracing stays off until this object is supplied.

Example

TypeScript
const posthog = new PostHog('phc_...', { traces: { serviceName: 'checkout-api' } })

Subject to change in a minor release.

Properties

PropertyTypeDescription
beforeSpanSend?BeforeSpanSendFn | BeforeSpanSendFn[]Experimental Runs on every finished span before it is queued. Edit the span in place, or return null to drop it. An array runs left to right, and the first hook to return null stops the chain. This is the place to scrub sensitive attributes, so a hook that throws drops the span rather than exporting an unscrubbed one. Example Drop health checks and redact a header traces: { beforeSpanSend: (span) => { if (span.attributes['http.route'] === '/health') return null delete span.attributes['http.request.header.authorization'] return span }, }
environment?stringExperimental Deployment environment (e.g. 'production', 'staging'), attached as OTLP deployment.environment.
flushIntervalMs?numberExperimental How often queued spans are flushed, in milliseconds. Spans also flush when the queue reaches maxExportBatchSize and on shutdown(). Default 5000
maxAttributesPerSpan?numberExperimental Maximum user-supplied attributes on a single span. Attributes the SDK attaches itself — posthogDistinctId, sessionId and friends — are exempt and are never evicted, because they are what links a span to a person and a session. On overflow the earliest-set attributes are kept and later ones are dropped, with the number dropped reported on the exported span. Default 128
maxAttributeValueLength?numberExperimental Maximum length of a string attribute value. Longer values are truncated, and the bound reaches every string the value contains, including the ones nested inside arrays and objects. It applies to span attributes, event attributes, span names, event names, status messages and resource attributes alike — including exception.stacktrace. The bound is what keeps one large value from making a span too large for the ingestion endpoint, which drops an oversized span whole. Default 8192
maxEventsPerSpan?numberExperimental Maximum events on a single span. On overflow the earliest events are kept and later ones are dropped, with the number dropped reported on the exported span. The cap is absolute: an exception event the SDK records on your behalf spends an ordinary slot like any other, so a span that fills its events and then throws keeps its error status but not the exception detail. Raise the cap on spans that record many events and can also fail. Default 128
maxExportBatchSize?numberExperimental Maximum spans per outbound request, and the queue depth that triggers an immediate flush. On a 413 the SDK halves this, retries the same spans, then ramps back up. Default 512
maxLiveSpans?numberExperimental Bound on how many spans may be live (started but not ended) at once. At the bound startSpan returns an inert handle, so code that leaks spans cannot grow the SDK's bookkeeping without limit. The SDK tracks only an id and a timestamp per live span, never the span itself, so a high bound is inexpensive. Default 10000
maxQueueSize?numberExperimental Bound on the in-memory export queue. When it is full the incoming span is dropped rather than evicting a queued one, whose children may already have been exported. Never lower than maxExportBatchSize. Default 2048
maxSpanAgeMs?numberExperimental Age at which a live span counts as leaked, in milliseconds. Checked only once maxLiveSpans is reached: spans this old are then evicted and never exported, and their slots are returned so one leak cannot disable tracing for the rest of the process. Below the bound, a long span that ends is exported as usual. Measured as monotonic elapsed time since startSpan, so a caller-supplied startTime neither ages a span early nor exempts it. Default 3600000
resourceAttributes?SpanAttributesExperimental Extra OTLP resource attributes attached to every batch. A string service.name, service.version or deployment.environment here wins over the serviceName / serviceVersion / environment fields — set it either way. telemetry.sdk.* is SDK-controlled and always wins.
serviceName?stringExperimental Name of the service producing these spans, attached as the OTLP service.name resource attribute. PostHog groups operations by service and span name, so this is what makes spans attributable. Default 'unknown_service'
serviceVersion?stringExperimental Service version, attached as OTLP service.version.

UnresolvedFlagReason

UnresolvedFlagReason = "experience_continuity" | "unsupported_definition" | "missing_context" | "unresolved_dependency"

Why local evaluation couldn't resolve a flag.

When more than one cause applies, the SDK reports the first matching reason in this order:

ReasonCause
experience_continuityThe flag uses experience continuity, which local evaluation can't resolve.
unsupported_definitionThe flag uses a rule local evaluation doesn't support, such as a static cohort, an unknown operator, or a circular or missing dependency.
unresolved_dependencyA dependency flag has a loaded definition but stayed unresolved.
missing_contextThe call didn't pass a person property, group property, or device ID the flag needs, or passed an unusable value.

UnsetPersonPropertiesMessage

UnsetPersonPropertiesMessage = object

Properties

PropertyTypeDescription
distinctIdstringUser distinct ID. Falls back to withContext() when missing or blank.
options?EventOptionsProcessing options sent with this event to capture v1.
propertiesstring | string[]Property name or list of property names to remove from the person profile ($unset).

V1EventOptions

The options object on a Capture V1 event: the caller's options plus any legacy $-prefixed option properties lifted by the transform. Values are sent unchanged. Always serialized as an object ({} when empty), never null.

Indexable

[key: string]: JsonType | undefined

Additional capture options, sent to capture v1 unchanged.

Properties

PropertyTypeDescription
cookieless_mode?booleanWhether to process this event in cookieless mode.
disable_skew_correction?booleanWhether to disable server-side timestamp skew correction for this event.
process_person_profile?booleanWhether to create or update a person profile for this event.

Without

Without<T> = { [K in keyof T]?: never }

Type Parameters

Type Parameter
T

Was this page useful?