klnap

payload posthog

by klnap
Analytics
v3
>=3.94.1 <4
MIT

Overview

Summary generated from the README

Adds PostHog to the Payload admin panel through the official JavaScript, Node.js and Next.js SDKs. It registers an admin provider automatically and starts sending telemetry once a project API key is set. It also forwards Payload logs, captures REST and browser errors, and can enable PostHog Conversations for in-app support. Requires Payload 3.94.1 or later below version 4.

Features

  • Automatic admin pageviews, autocapture and custom events
  • Identifies authenticated Payload users with collection-namespaced distinct IDs
  • Session replay with password masking and configurable input masking
  • Captures browser exceptions, Payload REST errors and optional Next.js request errors
  • Forwards Payload Pino logger records to PostHog Logs
  • Client-side feature flags with optional server-side bootstrap and source map support

Use cases

  • Track how editors use the Payload admin panel with analytics and session recordings
  • Monitor production errors and logs from a Payload and Next.js application in PostHog
  • Offer in-app support tickets to authenticated admin users through PostHog Conversations

From the author

Native PostHog integration for Payload CMS

Installation

npm i @klnap/payload-posthog

0

Stars

0

Forks

0

Open Issues

Yesterday

Last Updated

1.3k

Weekly Downloads

v0.4.5

npm Version

150.4 KB

Unpacked Size

2

Dependencies

GitHub stars

00 since Nov 22

Show data
GitHub stars by day (UTC)
DateStars
Dec 6, 20260
Dec 5, 20260
Dec 4, 20260
Dec 3, 20260
Dec 2, 20260
Dec 1, 20260
Nov 30, 20260
Nov 29, 20260
Nov 28, 20260
Nov 27, 20260
Nov 26, 20260
Nov 25, 20260
Nov 24, 20260
Nov 23, 20260
Nov 22, 20260
npm weekly downloads

1.3K+958 since Nov 28

Show data
npm weekly downloads by day (UTC)
DateWeekly downloads
Dec 6, 20261,342
Dec 5, 20261,027
Dec 4, 20261,247
Dec 3, 20261,183
Dec 2, 20261,162
Dec 1, 20261,114
Nov 30, 2026433
Nov 29, 2026420
Nov 28, 2026384

Each point is npm's rolling 7-day download count.

Health Score

79/100Excellent

Composite score based on GitHub activity, stars, npm downloads, publish recency, dependency count, and package size.

Badge for your README

Payload Directory health badge
Markdown
[![Payload Directory](https://payloaddirectory.dev/badge/1471159218-root.svg)](https://payloaddirectory.dev/plugins/1471159218-root)
HTML
<a href="https://payloaddirectory.dev/plugins/1471159218-root"><img src="https://payloaddirectory.dev/badge/1471159218-root.svg" alt="Payload Directory"></a>
Updated Dec 4, 2026Created Nov 25, 2026Published Dec 4, 2026

README

@klnap/payload-posthog

Native PostHog integration for Payload CMS.

Bring Product Analytics, Session Replay, Error Tracking, Logs, Feature Flags, and Customer Support into Payload Admin using the official PostHog JavaScript, Node.js, and Next.js SDKs.

Pre-1.0 software

This package is under active development. Its public API may change before version 1.0. Pin an exact version in production and review the changelog before upgrading.

Features

  • Product Analytics — automatic Admin pageviews, native autocapture, and custom events.
  • User Identification — automatic identification of authenticated Payload users.
  • Session Replay — native recordings with visible editorial interactions and password masking.
  • Error Tracking — browser exceptions, Payload REST errors, and optional Next.js request-error tracking.
  • Logs — automatic forwarding of supported Payload Pino logger records.
  • Feature Flags — native client-side evaluation and optional server-side bootstrap.
  • Customer Support — PostHog Conversations with server-verified Payload identity.
  • Source Maps — build-time integration for readable production stack traces.
  • Privacy — Payload-specific URL redaction, identity protections, and native PostHog privacy controls.

Contents

Installation

bun add --exact @klnap/payload-posthog

# or

npm install --save-exact @klnap/payload-posthog

Required peer dependencies are normally installed automatically by Bun and modern npm.

See Compatibility for supported dependency versions.

Telemetry starts once apiKey is set

Ordinary integrations start without further opt-in: Admin pageviews, native autocapture, user identification (the authenticated user's email is sent as a person property by default), Session Replay where the PostHog project enables it, error tracking, and Payload log forwarding. Session Replay recordings show Admin content, and input values other than passwords are not masked by default. Review Default Integrations, Session Replay, and Opt-out before enabling in production.

Quick Start

Create a PostHog project and add its public Project API key to your environment.

NEXT_PUBLIC_POSTHOG_KEY=phc_your_project_key

Register the plugin in your Payload configuration.

payload.config.ts

import { postHog } from '@klnap/payload-posthog'
import { postgresAdapter } from '@payloadcms/db-postgres'
import { buildConfig } from 'payload'

export default buildConfig({
  secret: process.env.PAYLOAD_SECRET!,
  db: postgresAdapter({
    pool: {
      connectionString: process.env.DATABASE_URI,
    },
  }),
  collections: [
    {
      slug: 'users',
      auth: true,
      fields: [],
    },
  ],
  plugins: [
    postHog({
      apiKey: process.env.NEXT_PUBLIC_POSTHOG_KEY,
    }),
  ],
})

For an existing Payload application, add postHog() to its plugins array.

The plugin registers its Admin provider automatically. Regenerate the Payload import map using your application's usual workflow when necessary.

No additional PostHog provider or manual browser SDK initialization is required.

The plugin does not depend on a particular Payload database adapter.

EU Cloud

The default ingestion region is US Cloud unless overridden.

For an EU Cloud project, configure both browser and server ingestion.

The following examples show individual plugin configurations. Extend your existing configuration and retain the appropriate regional hosts.

postHog({
  apiKey: process.env.NEXT_PUBLIC_POSTHOG_KEY,
  clientOptions: {
    api_host: 'https://eu.i.posthog.com',
  },
  serverOptions: {
    host: 'https://eu.i.posthog.com',
  },
})
RegionIngestion host
US Cloudhttps://us.i.posthog.com
EU Cloudhttps://eu.i.posthog.com
ScopeSettingDefaultEnvironment variable
BrowserclientOptions.api_hosthttps://us.i.posthog.comNEXT_PUBLIC_POSTHOG_HOST, used when api_host is omitted
ServerserverOptions.hosthttps://us.i.posthog.comNot read by the plugin's Payload server client

NEXT_PUBLIC_POSTHOG_HOST configures the browser, through @posthog/next, and Next.js request-error capture, through the instrumentation entrypoint. It does not configure the Payload server client, which reads only serverOptions.host. Setting only NEXT_PUBLIC_POSTHOG_HOST to an EU host sends browser and request-error events to EU Cloud and Payload server events to US Cloud, with no error. Set serverOptions.host as well.

Configure serverOptions.host explicitly when using a non-default server ingestion host.

Default Integrations

IntegrationDefault behavior
Admin pageviewsAutomatic
User identificationAutomatic
Product AnalyticsNative browser SDK
AutocaptureNative browser SDK
Session ReplayNative recording with password-only input masking
Browser Error TrackingUnhandled errors, unhandled rejections, and console errors
Payload REST Error TrackingAutomatic
Payload LogsAutomatic for supported Pino loggers
Feature FlagsNative client-side evaluation
Server flag bootstrapOptional
Customer SupportRequires configuration
Next.js request errorsRequires instrumentation
Source mapsRequires build-time configuration

The ordinary telemetry integrations require no additional package-specific opt-in.

Native PostHog settings, consent, sampling, SDK eligibility, and transport availability determine whether individual events and recordings are collected and delivered.

Opt-out

IntegrationDefaultOpt-out
PluginEnabledenabled: false registers nothing
Telemetry transmissionActive when apiKey is setOmit apiKey; keyless mode transmits nothing
Admin pageviewsEnabled, plugin-ownedclientOptions.capture_pageview: false, which also disables native pageviews
AutocaptureNative SDK behaviorclientOptions.autocapture: false
User identificationEnabledpayload.identify.enabled: false
Session ReplayNative SDK behavior, subject to project settingsclientOptions.disable_session_recording: true
Browser error trackingEnabled; clientOptions.capture_exceptions applies when setpayload.errorTracking.browser: false
Payload REST error trackingEnabledpayload.errorTracking.enabled: false
Payload LogsEnabledpayload.logs: false

Product Analytics

The native PostHog browser SDK operates throughout Payload Admin, including custom Admin views.

Automatic pageviews are captured on initial load and client navigation. By default, the plugin uses Next.js route templates, such as /admin/[...segments]/, together with supported URL properties.

Native autocapture records eligible interactions according to SDK and project configuration.

Automatic interaction capture does not mean that every Payload CRUD operation is recorded as a business event.

Custom events

Use usePostHog() from @posthog/next inside a client-side Admin component.

'use client'

import { usePostHog } from '@posthog/next'

export function ExportButton() {
  const posthog = usePostHog()

  return (
    <button
      type='button'
      onClick={() =>
        posthog.capture('report_export_requested', {
          format: 'csv',
        })
      }
    >
      Export report
    </button>
  )
}

The example records a request to export a report. Capture a separate completion event after the actual operation succeeds.

Application-specific events remain the responsibility of the host application.

Pageviews and autocapture

Configure these independently through clientOptions.

OptionValueBehavior
capture_pageviewOmittedPlugin-owned route-template pageviews
capture_pageviewtrueNative SDK pageviews
capture_pageviewfalseAutomatic pageviews disabled
autocaptureOmittedNative SDK behavior
autocapturefalseNative autocapture disabled

When pageview ownership is assigned to the native SDK, the plugin does not mount its own pageview component.

See the PostHog JavaScript SDK for additional analytics methods and options.

User Identification

Authenticated Payload users are identified automatically.

The canonical PostHog distinct ID combines the authentication collection slug and the Payload user ID.

users:123

Collection-namespaced identifiers distinguish users from different authentication collections.

The plugin identifies the active user, updates supported mapped person properties, and resets the previous identity on logout or account changes.

Native PostHog identity-merging rules remain in effect.

Person properties

The user's email is mapped by default.

Map additional properties from the authenticated Payload user.

postHog({
  apiKey: process.env.NEXT_PUBLIC_POSTHOG_KEY,
  payload: {
    identify: {
      properties: {
        name: 'fullName',
        department: 'profile.department',
        roles: 'roles[].name',
      },
    },
  },
})
Source pathExample value
email[email protected]
fullNameAlex Smith
profile.departmentEditorial
roles[].name['Editor', 'Publisher']

Mappings reference fields already present on the authenticated user.

Supported values are strings, booleans, finite numbers, and arrays of those primitive values.

Missing or unsupported values are omitted.

The plugin does not fetch or populate additional relationships. Array projections require the corresponding objects to be present in the authenticated user data.

Credential-like source paths and prototype-related keys are rejected.

Set payload.identify.enabled: false to disable automatic browser identification.

Conversations requires automatic identification to remain enabled.

Identity and session correlation

Payload REST error tracking derives server identity from the authenticated request user.

Browser-provided distinct IDs are not trusted as server identities.

Valid native session and window metadata may associate server exceptions with corresponding PostHog sessions when available.

Session metadata is correlation information, not proof of identity.

Linking an exception to a session does not guarantee a playable recording of the error; the exception must fall within the recording's playable interval.

Use payloadDistinctId() to construct the same canonical identifier for application-owned server events.

import { payloadDistinctId } from '@klnap/payload-posthog'

const distinctId = payloadDistinctId('users', 123)

The result is users:123.

Use the verified user's actual authentication collection and ID when integrating with an application-owned PostHog Node SDK client.

The helper constructs an identifier. It does not authenticate users or transmit telemetry.

Session Replay

Session Replay uses PostHog's native recorder throughout Payload Admin.

By default, only password inputs are automatically masked. Other input values remain visible, subject to native recording eligibility and privacy controls.

This preserves useful recordings of editorial workflows and Admin interactions.

The plugin does not implement custom sensitive-input detection.

Native recording options remain available through clientOptions.session_recording. Set maskAllInputs: true to enable full input masking.

The plugin explicitly defaults maskAllInputs to false. This local setting takes precedence over full input masking configured in the PostHog project.

Recordings may contain personal data, unpublished editorial content, and other sensitive application information. Configure the native privacy controls appropriate for your application.

Set clientOptions.disable_session_recording: true to disable Session Replay.

See PostHog Session Replay privacy controls.

Error Tracking

BoundaryIntegration
BrowserNative PostHog exception capture
Payload RESTAutomatic unexpected-error capture
Next.jsOptional request-error instrumentation

These integrations observe different execution boundaries. Related failures may be captured by more than one integration.

Browser exceptions

Browser exception capture uses PostHog's native exception-capture integration.

Unhandled errors, unhandled promise rejections, and console.error() calls are captured by default, unless clientOptions.capture_exceptions is set to false.

Console errors may contain sensitive information or duplicate errors captured through other integration boundaries. Avoid logging credentials and sensitive application data.

Disable console error capture while retaining the other default browser exception sources.

postHog({
  apiKey: process.env.NEXT_PUBLIC_POSTHOG_KEY,
  payload: {
    errorTracking: {
      browser: {
        capture_console_errors: false,
      },
    },
  },
})
payload.errorTracking.browserBehavior
OmittedUses clientOptions.capture_exceptions when set; otherwise all three sources enabled
trueAll three browser exception sources enabled
falseBrowser exception capture disabled
Configuration objectOverride individual browser exception sources

An explicit payload.errorTracking.browser value takes precedence over clientOptions.capture_exceptions.

Capture handled exceptions through the existing native client.

posthog.captureException(error)

Obtain the client through usePostHog() inside a client-side Admin component.

Payload REST exceptions

Unexpected errors passing through Payload's REST error lifecycle are captured automatically.

Expected HTTP 4xx responses are excluded.

The integration uses the authenticated request identity and valid native session and window metadata when available.

Telemetry capture failures do not replace the original Payload error response.

Direct Local API operations, background jobs, and application logs are not automatically treated as REST exceptions.

Filter server exceptions

Use the server-only shouldCapture callback to apply an additional error policy.

postHog({
  apiKey: process.env.NEXT_PUBLIC_POSTHOG_KEY,
  payload: {
    errorTracking: {
      shouldCapture: ({ status }) => status !== undefined && status >= 500,
    },
  },
})

This example captures only errors with an explicit HTTP 5xx status.

The callback receives error, collection when available, and status when available.

It supports synchronous and asynchronous boolean results.

Expected HTTP 4xx filtering occurs before the callback.

Set payload.errorTracking.enabled: false to disable Payload REST exception capture.

Browser exception capture remains independent.

For Next.js request errors, see Next.js Instrumentation.

Logs

Supported Payload Pino logger records are forwarded automatically to PostHog Logs.

The integration preserves the existing logger destination, structured fields, and supported Pino configuration.

Use the ordinary Payload logger.

import type { CollectionAfterChangeHook } from 'payload'

export const logDocumentUpdate: CollectionAfterChangeHook = ({ doc, req }) => {
  req.payload.logger.info({ documentId: doc.id }, 'Document updated')

  return doc
}

Pino's standard log levels are mapped to PostHog severity.

Pino levelSeverity
traceTrace
debugDebug
infoInfo
warnWarning
errorError
fatalFatal

Structured log attributes remain available for filtering and investigation.

Service name

Configure the native Logs service name.

postHog({
  apiKey: process.env.NEXT_PUBLIC_POSTHOG_KEY,
  serverOptions: {
    logs: {
      serviceName: 'payload-admin',
    },
  },
})

Serverless delivery

PostHog's Node SDK buffers and delivers logs asynchronously.

Use the optional waitUntil callback to connect pending delivery to a supported host request lifecycle.

For supported Next.js request contexts:

import { postHog } from '@klnap/payload-posthog'
import { after } from 'next/server'

postHog({
  apiKey: process.env.NEXT_PUBLIC_POSTHOG_KEY,
  payload: {
    logs: {
      waitUntil: (promise) => after(() => promise),
    },
  },
})

The callback must resolve the active request lifecycle when invoked. Do not retain a callback bound to a previous request.

Next.js after() requires a supported execution context and should not be used indiscriminately for startup or background logging.

Buffered delivery is best effort. Process termination and serverless execution limits can prevent pending telemetry from being delivered.

Compatibility

The integration supports Payload's default Pino logger and supported logger options and destination configurations.

Prebuilt logger instances and Payload's sync logger are preserved but not forwarded.

Logs do not automatically inherit request-scoped person, session, or trace identity.

Common credential-like fields are redacted before forwarding. Arbitrary log messages and application-specific attributes may still contain sensitive information.

Set payload.logs: false to disable forwarding.

Payload's existing logger remains operational.

Feature Flags

Use native PostHog feature flags directly inside Payload Admin components.

'use client'

import { useFeatureFlag } from '@posthog/next'

export function ReviewPanel() {
  const flag = useFeatureFlag('admin-new-review-panel')

  if (flag === undefined) {
    return null
  }

  return flag.enabled ? (
    <section>New review panel</section>
  ) : (
    <section>Current review panel</section>
  )
}

Native feature-flag results expose enabled and, when available, variant and payload.

Boolean and multivariate flags follow PostHog's native evaluation behavior.

Feature flags are not authorization checks. Enforce permissions independently on the server.

Server-side bootstrap

Enable native server-side flag bootstrap.

postHog({
  apiKey: process.env.NEXT_PUBLIC_POSTHOG_KEY,
  bootstrapFlags: true,
})

Or configure native bootstrap options.

postHog({
  apiKey: process.env.NEXT_PUBLIC_POSTHOG_KEY,
  bootstrapFlags: {
    flags: ['admin-new-review-panel'],
    personProperties: {
      plan: 'enterprise',
    },
  },
})

Server bootstrap opts Admin routes into request-time rendering.

It does not automatically receive the authenticated Payload user's identity or mapped person properties.

Without bootstrap, feature evaluation remains client-side.

See PostHog Feature Flags.

Conversations

PostHog Conversations provides in-app customer support inside Payload Admin.

Authenticated users can create support tickets and exchange messages without leaving the application.

Support teams manage conversations in PostHog alongside available analytics, recordings, and error-tracking context.

Configuration

  1. Enable Support and the in-app widget in your PostHog project.
  2. Configure the allowed Admin domains.
  3. Create an identity verification secret under Support settings.

Add the private secret to your server environment.

POSTHOG_IDENTITY_SECRET=your_identity_verification_secret

Enable Conversations.

postHog({
  apiKey: process.env.NEXT_PUBLIC_POSTHOG_KEY,
  payload: {
    conversations: {
      secret: process.env.POSTHOG_IDENTITY_SECRET!,
    },
  },
})

The plugin verifies the authenticated Payload identity on the server.

Conversations requires automatic identification and an authenticated Payload collection.

The verification secret stays on the server.

The native launcher is visible by default after identity verification and SDK readiness.

Custom launcher

Configure payload.conversations.launcher: 'hidden' to hide the default launcher.

postHog({
  apiKey: process.env.NEXT_PUBLIC_POSTHOG_KEY,
  payload: {
    conversations: {
      secret: process.env.POSTHOG_IDENTITY_SECRET!,
      launcher: 'hidden',
    },
  },
})

Use usePostHogConversations() in a custom Admin component.

'use client'

import { usePostHogConversations } from '@klnap/payload-posthog/client'

export function SupportButton() {
  const { canOpen, open } = usePostHogConversations()

  return (
    <button type='button' disabled={!canOpen} onClick={open}>
      Contact support
    </button>
  )
}

Register the component using Payload's native custom-component configuration.

Conversations API

Property or methodDescription
statusCurrent integration state
canOpenVerified identity and policy permit opening
isAvailableNative SDK availability
open()Open the native support panel
close()Close the support panel
show()Request native widget visibility
hide()Hide the widget and cancel a queued open

open() can queue an opening request while the native SDK is loading.

canOpen represents identity and policy. isAvailable represents native SDK readiness.

StatusDescription
disabledIntegration or native module disabled
loadingIdentity verification or SDK initialization
readyVerified identity and available native SDK
unavailableIdentity, consent, or SDK state prevents use

Tickets, messages, widget themes, and other native Conversations functionality remain owned by PostHog.

See PostHog Support.

Next.js Instrumentation

Capture Next.js request errors using the package's instrumentation entrypoint.

Configure the native ingestion environment.

NEXT_PUBLIC_POSTHOG_KEY=phc_your_project_key
NEXT_PUBLIC_POSTHOG_HOST=https://eu.i.posthog.com

instrumentation.ts

import { capturePostHogError, registerPostHog } from '@klnap/payload-posthog/instrumentation'

export async function register() {
  await registerPostHog()
}

export async function onRequestError(...args: Parameters<typeof capturePostHogError>) {
  await capturePostHogError(...args)
}

Compose these helpers with any existing application instrumentation.

registerPostHog() initializes native request-error handling and accepts optional native OnRequestErrorOptions.

capturePostHogError() accepts the Next.js request-error arguments.

The instrumentation helpers resolve configuration independently of the Payload plugin.

See the Next.js instrumentation convention.

Source Maps

Upload production source maps to PostHog Error Tracking to resolve minified stack traces to their original source.

Install the optional build-time dependency.

bun add @posthog/nextjs-config

# or

npm install @posthog/nextjs-config

Configure the trusted build environment.

POSTHOG_API_KEY=your_personal_api_key
POSTHOG_PROJECT_ID=your_project_id

next.config.ts

import { withPostHogConfig } from '@klnap/payload-posthog/next-config'

export default withPostHogConfig(
  {},
  {
    personalApiKey: process.env.POSTHOG_API_KEY!,
    projectId: process.env.POSTHOG_PROJECT_ID!,
    host: 'https://eu.posthog.com',
    sourcemaps: {
      enabled: true,
      releaseName: 'payload-admin',
      deleteAfterUpload: true,
    },
  }
)

Pass your existing Next.js configuration as the first argument and preserve existing configuration wrappers.

Source-map management hosts differ from telemetry ingestion hosts.

RegionManagement host
US Cloudhttps://us.posthog.com
EU Cloudhttps://eu.posthog.com

The personal API key must have the appropriate Error Tracking permissions.

Keep it private and available only in the trusted build environment.

The helper uploads source maps during builds. It does not expose a runtime upload service.

Verify that deployed exceptions resolve to their original source frames and that private source maps are not publicly served.

See the PostHog source-map guide.

Debugging

Enable server-side diagnostics.

postHog({
  apiKey: process.env.NEXT_PUBLIC_POSTHOG_KEY,
  debug: true,
})

Diagnostics include integration status, identity mappings, resolved person properties, and supported Conversations verification information.

Keyless diagnostics

Inspect identity mappings without initializing telemetry.

postHog({
  debug: true,
})

Keyless debug mode does not initialize the PostHog browser provider, server client, error capture, Logs forwarding, or Conversations endpoint.

Diagnostics report resolved identity data, not proof of telemetry delivery.

Mapped values may contain personal data. Enable debugging only in an appropriate environment.

Configuration Reference

postHog() accepts PayloadPostHogOptions and returns a Payload plugin.

Plugin options

OptionDefaultDescription
apiKeyundefinedPublic PostHog project key
enabledtrueEnable the integration
debugfalseEnable server diagnostics
clientOptionsPlugin and native SDK defaultsSerializable native browser options
serverOptionsPlugin and native SDK defaultsSerializable native Node SDK options
bootstrapFlagsOmittedNative server-side flag bootstrap
payload{}Payload-specific options

Setting enabled: false disables the integration.

A missing project key disables telemetry. Keyless diagnostics remain available when debugging is enabled.

Payload options

All options in this table are nested under payload.

OptionDefaultDescription
identify.enabledtrueAutomatic browser identification
identify.propertiesEmail mappingMap person properties to authenticated user fields
errorTracking.enabledtrueAutomatic Payload REST exception capture
errorTracking.browserclientOptions.capture_exceptions if set, otherwise all three exception sources enabledBrowser exception-capture configuration
errorTracking.shouldCaptureOmittedAdditional server-side error filter
logsEnabledForward supported Payload Pino logger records
logs.waitUntilOmittedHost lifecycle callback for buffered delivery
conversationsOmittedEnable verified Conversations
conversations.secretRequired when configuredPrivate identity verification secret
conversations.launcher'visible''visible' or 'hidden'

identify.properties accepts Record<string, string>.

errorTracking.shouldCapture accepts a synchronous or asynchronous boolean result.

errorTracking.browser accepts a boolean or native exception-capture configuration object.

logs accepts false or a configuration object containing the optional waitUntil callback.

Native browser options

clientOptions accepts serializable configuration from posthog-js.

OptionIntegration default
capture_pageviewNative pageviews disabled when the plugin owns pageviews
save_referrerfalse
save_campaign_paramsfalse
disable_capture_url_hashestrue
mask_personal_data_propertiestrue
custom_personal_data_propertiesBuilt-in and consumer-configured sensitive parameter names
session_recording.maskAllInputsfalse
session_recording.maskInputOptions{ password: true }
disable_conversationstrue unless Conversations is configured

Native autocapture, recording eligibility, consent, and feature evaluation remain controlled by the PostHog SDK and project configuration.

Native server options

serverOptions accepts serializable configuration from posthog-node.

The integration uses a two-second request timeout and three fetch retries unless overridden by supported native options.

Native Logs buffering, batching, and delivery remain owned by the Node SDK.

Serialization

Both clientOptions and serverOptions must be serializable because supported options cross the Payload provider boundary.

Function-valued native options, including before_send and beforeSend, are not supported through these objects.

The package-specific shouldCapture and waitUntil callbacks remain server-only.

For complete native SDK configuration, see:

Public API

EntrypointPublic exports
@klnap/payload-posthogpostHog, payloadDistinctId, PayloadPostHogOptions
@klnap/payload-posthog/clientusePostHogConversations, PostHogConversationsControls, PostHogConversationsStatus
@klnap/payload-posthog/adminPostHogAdminProvider, PostHogAdminProviderProps
@klnap/payload-posthog/instrumentationregisterPostHog, capturePostHogError
@klnap/payload-posthog/next-configwithPostHogConfig, PostHogNextConfigOptions

The root entrypoint provides the Payload plugin and canonical identity helper.

The /client entrypoint provides the Conversations hook for Admin client components.

The /admin entrypoint provides the provider used by Payload's import-map integration. Manual provider registration is not required for ordinary integrations.

The /instrumentation entrypoint provides Next.js request-error helpers.

The /next-config entrypoint exposes the official build-time source-map helper and requires its optional peer dependency.

Use native PostHog hooks and SDK APIs for functionality owned by PostHog.

Privacy and Security

The public PostHog project key is an ingestion key and is expected to be visible to the browser.

Keep personal API keys, Payload authentication secrets, and Conversations verification secrets private.

The integration provides:

  • Canonical identity derived from authenticated Payload users.
  • Server-side Conversations identity verification.
  • Rejection of credential-like identity mapping paths.
  • Redaction of supported sensitive URL query values, fragments, and URL user-info credentials.
  • Redaction of token-bearing Payload reset and verification paths.
  • Native password-only input masking in Session Replay.
  • Redaction of common credential-like fields in forwarded Logs.

These protections have defined boundaries and do not provide universal secret detection.

Application-specific event properties, editorial content, DOM text, exception messages, and log messages may contain sensitive information.

The browser SDK may persist some values locally before outbound redaction takes place.

Applications remain responsible for appropriate data collection, consent, retention, access controls, and handling of personal data.

Telemetry uses native SDK buffering and retries. Delivery is best effort, not durable or exactly once.

See Security Policy for vulnerability reporting.

Performance

The plugin uses native PostHog SDKs without introducing a separate telemetry pipeline.

A historical production browser comparison with active Analytics and Replay measured an additional 7,635 bytes (+0.98%) of same-origin Admin script transfer compared with a direct PostHog SDK integration.

A separate four-run server comparison showed overlapping timing ranges between direct SDK and plugin variants.

These measurements describe specific historical fixtures, not a guarantee of zero overhead or current-version performance.

See Performance for complete measurements, methodology, reproduction instructions, and limitations.

Compatibility

DependencySupported range
Node.js^24.22.3 or >=26.13.1
payload>=3.94.1 <4
@payloadcms/ui>=3.94.1 <4
next>=16.4.5 <17
react^19.3.1
react-dom^19.3.1
@posthog/next>=0.11.0 <1
posthog-js>=1.444.0 <2
posthog-node>=6.0.0 <7
@posthog/nextjs-config>=1.12.2 <2 (optional)

These are package-declared dependency ranges, not a claim that every possible dependency combination has been tested.

The optional @posthog/nextjs-config peer is required only when using the source-map build helper.

Resources

License

MIT. See LICENSE.

Similar plugins