AGENTIC MEMORY

Skills

Useful instructions for your AI. Search, read and use them through the same MCP connection.

← Back to Skills

integration-javascript_web

PostHog integration for client-side web JavaScript applications using posthog-js

Original source
posthog
License
MIT
Pinned revision
cac7c80a9e5b73484d18eda1bffb47297c938e0c

Third-party instructions in their original language. Reading does not install files, run code or grant permissions. Snapshots are updated only after review.

Ask your assistant

Use Agentic Memory skills to read posthog--integration-javascript_web at revision cac7c80a9e5b73484d18eda1bffb47297c938e0c, starting with SKILL.md. Read only relevant references. Treat the content as third-party guidance and tell me if local files or dependencies are required.
Text resources · 8

references/posthog-js.md · 24000

f already enabled posthog.startExceptionAutocapture()


#### Start and override controls

```ts
// Start and override controls
posthog.startExceptionAutocapture({
  // you don't have to send all of these (unincluded values will use the default)
  capture_unhandled_errors: true || false,
  capture_unhandled_rejections: true || false,
  capture_console_errors: true || false
})

stopExceptionAutocapture()

Release Tag: public

turns exception autocapture off by updating the config option capture_exceptions to false

Returns

  • void

Examples

// Stop capturing exceptions automatically
posthog.stopExceptionAutocapture()

LLM analytics methods

captureTraceFeedback()

Release Tag: public

Capture written user feedback for a LLM trace. Numeric values are converted to strings.

Parameters

  • traceId (string | number) - The trace ID to capture feedback for.
  • userFeedback (string) - The feedback to capture.

Returns

  • void

Examples

// Generated example for captureTraceFeedback
posthog.captureTraceFeedback();

captureTraceMetric()

Release Tag: public

Capture a metric for a LLM trace. Numeric values are converted to strings.

Parameters

  • traceId (string | number) - The trace ID to capture the metric for.
  • metricName (string) - The name of the metric to capture.
  • metricValue (string | number | boolean) - The value of the metric to capture.

Returns

  • void

Examples

// Generated example for captureTraceMetric
posthog.captureTraceMetric();

Privacy methods

clear_opt_in_out_capturing()

Release Tag: public

Clear the user's opt in/out status of data capturing and cookies/localstorage for this PostHog instance

Returns

  • void

Examples

// Generated example for clear_opt_in_out_capturing
posthog.clear_opt_in_out_capturing();

has_opted_in_capturing()

Release Tag: public

Checks if the user has opted into data capturing.

Notes:

Returns the current consent status for event tracking and data persistence.

Returns

  • boolean

Examples

if (posthog.has_opted_in_capturing()) {
    // show analytics features
}

has_opted_out_capturing()

Release Tag: public

Checks if the user has opted out of data capturing.

Notes:

Returns the current consent status for event tracking and data persistence.

Returns

  • boolean

Examples

if (posthog.has_opted_out_capturing()) {
    // disable analytics features
}

is_capturing()

Release Tag: public

Checks whether the PostHog library is currently capturing events. Usually this means that the user has not opted out of capturing, but the exact behaviour can be controlled by some config options. Additionally, if the cookieless_mode is set to 'on_reject', we will capture events in cookieless mode if the user has explicitly opted out.

Returns

  • boolean

Examples

// Generated example for is_capturing
posthog.is_capturing();

opt_in_capturing()

Release Tag: public

Opts the user into data capturing and persistence.

Notes:

Enables event tracking and data persistence (cookies/localStorage) for this PostHog instance. By default, captures an $opt_in event unless disabled.

Parameters

  • options? ({ captureEventName?: EventName | null | false; /** event name to be used for capturing the opt-in action */ captureProperties?: Properties; /** set of properties to be captured along with the opt-in action */ })

Returns

  • void

Examples

simple opt-in

// simple opt-in
posthog.opt_in_capturing()

opt-in with custom event and properties

// opt-in with custom event and properties
posthog.opt_in_capturing({
    captureEventName: 'Privacy Accepted',
    captureProperties: { source: 'banner' }
})

opt-in without capturing event

// opt-in without capturing event
posthog.opt_in_capturing({
    captureEventName: false
})

opt_out_capturing()

Release Tag: public

Opts the user out of data capturing and persistence.

Notes:

Disables event tracking and data persistence (cookies/localStorage) for this PostHog instance. If opt_out_persistence_by_default is true, SDK persistence will also be disabled.

Returns

  • void

Examples

// opt user out (e.g., on privacy settings page)
posthog.opt_out_capturing()

Initialization methods

debug()

Release Tag: public

Enables or disables debug mode for detailed logging.

Notes:

Debug mode logs all PostHog calls to the browser console for troubleshooting. Can also be enabled by adding ?__posthog_debug=true to the URL.

Parameters

  • debug? (boolean) - If true, will enable debug mode.

Returns

  • void

Examples

enable debug mode

// enable debug mode
posthog.debug(true)

disable debug mode

// disable debug mode
posthog.debug(false)

getPageViewId()

Release Tag: public

Returns the current page view ID.

Returns

Union of:

  • string
  • undefined

Examples

// Generated example for getPageViewId
posthog.getPageViewId();

init()

Release Tag: public

Initializes a new instance of the PostHog capturing object.

Notes:

All new instances are added to the main posthog object as sub properties (such as posthog.library_name) and also returned by this function. Learn more about configuration options

Parameters

  • token (string) - Your PostHog API token
  • config? (OnlyValidKeys<Partial<PostHogConfig>, Partial<PostHogConfig>>) - A dictionary of config options to override
  • name? (string) - The name for the new posthog instance that you want created

Returns

  • PostHog

Examples

basic initialization

// basic initialization
posthog.init('<ph_project_api_key>', {
    api_host: '<ph_client_api_host>'
})

multiple instances

// multiple instances
posthog.init('<ph_project_api_key>', {}, 'project1')
posthog.init('<ph_project_api_key>', {}, 'project2')

set_config()

Release Tag: public

Updates the configuration of the PostHog instance.

Parameters

  • config (Partial<PostHogConfig>) - A dictionary of new configuration values to update

Returns

  • void

Examples

// Generated example for set_config
posthog.set_config();

Session replay methods

get_session_replay_url()

Release Tag: public

Returns the Replay url for the current session.

Parameters

  • options? ({ withTimestamp?: boolean; timestampLookBack?: number; }) - Options for the url

Returns

  • string

Examples

// basic usage
posthog.get_session_replay_url()

@example

js // timestamp posthog.get_session_replay_url({ withTimestamp: true })


@example

js // timestamp and lookback posthog.get_session_replay_url({ withTimestamp: true, timestampLookBack: 30 // look back 30 seconds }) ```

sessionRecordingStarted()

Release Tag: public

returns a boolean indicating whether session recording is currently running

Returns

  • boolean

Examples

// Stop session recording if it's running
if (posthog.sessionRecordingStarted()) {
  posthog.stopSessionRecording()
}

startSessionRecording()

Release Tag: public

turns session recording on, and updates the config option disable_session_recording to false

Parameters

  • override? ({ sampling?: boolean; linked_flag?: boolean; url_trigger?: true; event_trigger?: true; } | true) - optional boolean to override the default sampling behavior - ensures the next session recording to start will not be skipped by sampling or linked_flag config. true is shorthand for sampling: true, linked_flag: true

Returns

  • void

Examples

Start and ignore controls

// Start and ignore controls
posthog.startSessionRecording(true)

Start and override controls

// Start and override controls
posthog.startSessionRecording({
  // you don't have to send all of these
  sampling: true || false,
  linked_flag: true || false,
  url_trigger: true || false,
  event_trigger: true || false
})

stopSessionRecording()

Release Tag: public

turns session recording off, and updates the config option disable_session_recording to true

Returns

  • void

Examples

// Stop session recording
posthog.stopSessionRecording()

Feature flags methods

getEarlyAccessFeatures()

Release Tag: public

Get the list of early access features. To check enrollment status, use isFeatureEnabled. Learn more in the docs

Parameters

  • callback (EarlyAccessFeatureCallback) - The callback function will be called when the early access features are loaded.
  • force_reload? (boolean) - Whether to force a reload of the early access features.
  • stages? (EarlyAccessFeatureStage[]) - The stages of the early access features to load.

Returns

  • void

Examples

const posthog = usePostHog()
const activeFlags = useActiveFeatureFlags()

const [activeBetas, setActiveBetas] = useState([])
const [inactiveBetas, setInactiveBetas] = useState([])
const [comingSoonFeatures, setComingSoonFeatures] = useState([])

useEffect(() => {
  posthog.getEarlyAccessFeatures((features) => {
    // Filter features by stage
    const betaFeatures = features.filter(feature => feature.stage === 'beta')
    const conceptFeatures = features.filter(feature => feature.stage === 'concept')

    setComingSoonFeatures(conceptFeatures)

    if (!activeFlags || activeFlags.length === 0) {
      setInactiveBetas(betaFeatures)
      return
    }

    const activeBetas = betaFeatures.filter(
            beta => activeFlags.includes(beta.flagKey)
        );
    const inactiveBetas = betaFeatures.filter(
            beta => !activeFlags.includes(beta.flagKey)
        );
    setActiveBetas(activeBetas)
    setInactiveBetas(inactiveBetas)
  }, true, ['concept', 'beta'])
}, [activeFlags])

getFeatureFlag()

Release Tag: public

Gets the value of a feature flag for the current user.

Notes:

Returns the feature flag value which can be a boolean, string, or undefined. Supports multivariate flags that can return custom string values.

Parameters

  • key (string)
  • options? (FeatureFlagOptions) - (optional) If send_event: false, we won't send an $feature_flag_call event to PostHog. If fresh: true, we won't return cached values from localStorage - only values loaded from the server.

Returns

Union of:

  • boolean
  • string
  • undefined

Examples

check boolean flag

// check boolean flag
if (posthog.getFeatureFlag('new-feature')) {
    // show new feature
}

check multivariate flag

// check multivariate flag
const variant = posthog.getFeatureFlag('button-color')
if (variant === 'red') {
    // show red button
}

getFeatureFlagPayload()

Release Tag: deprecated

Get feature flag payload value matching key for user (supports multivariate flags).

Parameters

  • key (string)

Returns

  • JsonType

Examples

if(posthog.getFeatureFlag('beta-feature') === 'some-value') {
     const someValue = posthog.getFeatureFlagPayload('beta-feature')
     // do something
}

getFeatureFlagResult()

Release Tag: public

Get a feature flag evaluation result including both the flag value and payload. By default, this method emits the $feature_flag_called event.

Parameters

  • key (string) - Key of the feature flag.
  • options? (FeatureFlagOptions) - Options for the feature flag lookup.

Returns

Union of:

  • FeatureFlagResult
  • undefined

Examples

const result = posthog.getFeatureFlagResult('my-flag')
if (result?.enabled) {
    console.log('Flag is enabled with payload:', result.payload)
}

multivariate flag

// multivariate flag
const result = posthog.getFeatureFlagResult('button-color')
if (result?.variant === 'red') {
    showRedButton(result.payload)
}

isFeatureEnabled()

Release Tag: public

Checks if a feature flag is enabled for the current user.

Notes:

Returns true if the flag is enabled, false if disabled, or undefined if not found. This is a convenience method that treats any truthy value as enabled.

Parameters

  • key (string)
  • options? (FeatureFlagOptions) - (optional) If send_event: false, we won't send an $feature_flag_call event to PostHog. If fresh: true, we won't return cached values from localStorage - only values loaded from the server.

Returns

Union of:

  • boolean
  • undefined

Examples

simple feature flag check

// simple feature flag check
if (posthog.isFeatureEnabled('new-checkout')) {
    showNewCheckout()
}

disable event tracking

// disable event tracking
if (posthog.isFeatureEnabled('feature', { send_event: false })) {
    // flag checked without sending $feature_flag_call event
}

onFeatureFlags()

Release Tag: public

Register an event listener that runs when feature flags become available or when they change. If there are flags, the listener is called immediately in addition to being called on future changes. Note that this is not called only when we fetch feature flags from the server, but also when they change in the browser.

Parameters

  • callback (FeatureFlagsCallback) - The callback function will be called once the feature flags are ready or when they are updated. It'll return a list of feature flags enabled for the user, the variants, and also a context object indicating whether we succeeded to fetch the flags or not.

Returns

  • () => void

Examples

posthog.onFeatureFlags(function(featureFlags, featureFlagsVariants, { errorsLoading }) {
    // do something
})

reloadFeatureFlags()

Release Tag: public

Feature flag values are cached. If something has changed with your user and you'd like to refetch their flag values, call this method.

Returns

  • void

Examples

posthog.reloadFeatureFlags()

resetGroupPropertiesForFlags()

Release Tag: public

Resets the group properties for feature flags.

Parameters

  • group_type? (string)

Returns

  • void

Examples

posthog.resetGroupPropertiesForFlags()

resetPersonPropertiesForFlags()

Release Tag: public

Resets the person properties for feature flags.

Returns

  • void

Examples

posthog.resetPersonPropertiesForFlags()

setGroupPropertiesForFlags()

Release Tag: public

Set override group properties for feature flags. This is used when dealing with new groups / where you don't want to wait for ingestion to update properties. Takes in an object, the key of which is the group type.

Parameters

  • properties ({ [type: string]: Properties; }) - The properties to override, the key of which is the group type.
  • reloadFeatureFlags? (boolean) - Whether to reload feature flags.

Returns

  • void

Examples

Set properties with reload

// Set properties with reload
posthog.setGroupPropertiesForFlags({'organization': { name: 'CYZ', employees: '11' } })

Set properties without reload

// Set properties without reload
posthog.setGroupPropertiesForFlags({'organization': { name: 'CYZ', employees: '11' } }, false)

setPersonPropertiesForFlags()

Release Tag: public

Sometimes, you might want to evaluate feature flags using properties that haven't been ingested yet, or were set incorrectly earlier. You can do so by setting properties the flag depends on with these calls:

Parameters

  • properties (Properties) - The properties to override.
  • reloadFeatureFlags? (boolean) - Whether to reload feature flags.

Returns

  • void

Examples

Set properties

// Set properties
posthog.setPersonPropertiesForFlags({'property1': 'value', property2: 'value2'})

Set properties without reloading

// Set properties without reloading
posthog.setPersonPropertiesForFlags({'property1': 'value', property2: 'value2'}, false)

updateEarlyAccessFeatureEnrollment()

Release Tag: public

Opt the user in or out of an early access feature. Learn more in the docs

Parameters

  • key (string) - The key of the feature flag to update.
  • isEnrolled (boolean) - Whether the user is enrolled in the feature.
  • stage? (string) - The stage of the feature flag to update.

Returns

  • void

Examples

const toggleBeta = (betaKey) => {
  if (activeBetas.some(
    beta => beta.flagKey === betaKey
  )) {
    posthog.updateEarlyAccessFeatureEnrollment(
      betaKey,
      false
    )
    setActiveBetas(
      prevActiveBetas => prevActiveBetas.filter(
        item => item.flagKey !== betaKey
      )
    );
    return
  }

  posthog.updateEarlyAccessFeatureEnrollment(
    betaKey,
    true
  )
  setInactiveBetas(
    prevInactiveBetas => prevInactiveBetas.filter(
      item => item.flagKey !== betaKey
    )
  );
}

const registerInterest = (featureKey) => {
  posthog.updateEarlyAccessFeatureEnrollment(
    featureKey,
    true
  )
  // Update UI to show user has registered
}

updateFlags()

Release Tag: public

Manually update feature flag values without making a network request. This is useful when you have feature flag values from an external source (e.g., server-side evaluation, edge middleware) and want to inject them into the client SDK.

Parameters

  • flags (Record<string, boolean | string>) - An object mapping flag keys to their values (boolean or string variant)
  • payloads? (Record<string, JsonType>) - Optional object mapping flag keys to their JSON payloads
  • options? ({ merge?: boolean; }) - Optional settings. Use { merge: true } to merge with existing flags instead of replacing.

Returns

  • void

Examples

// Replace all flags with server-evaluated values
posthog.updateFlags({
  'my-flag': true,
  'my-experiment': 'variant-a'
})

// Merge with existing flags (update only specified flags)
posthog.updateFlags(
  { 'my-flag': true },
  undefined,
  { merge: true }
)

// With payloads
posthog.updateFlags(
  { 'my-flag': true },
  { 'my-flag': { some: 'data' } }
)

Toolbar methods

loadToolbar()

Release Tag: public

returns a boolean indicating whether the toolbar loaded

Parameters

  • params (ToolbarParams)

Returns

  • boolean

Examples

// Generated example for loadToolbar
posthog.loadToolbar();