JavaScript web usage

After setup, the SDK captures pageviews, clicks, and form interactions automatically. Add explicit calls for custom events, login, logout, feature flags, surveys, and errors.

See Version 1.x.x for full method signatures, parameters, and configuration types.

Capture key events

Send custom events with capture when a user finishes a key action:

Web
posthog.capture('checkout_completed', { plan: 'pro' })

Send before page unload

The SDK batches events in memory and flushes them every few seconds, so navigating away or reloading can drop queued events.

Pass the beacon transport and instant flush flags to capture on clicks or form submits that unload the page, so the browser finishes sending:

Web
posthog.capture(
'clicked_checkout',
{ source: 'header' },
{ transport: 'sendBeacon', send_instantly: true }
)

You need both options together. Choosing the beacon transport without an instant flush still queues the event.

Before login: anonymous events

Before identify, PostHog generates a UUID in browser storage and attaches $is_identified: false and $process_person_profile: false to every event. PostHog doesn't create a person profile, so it stores only the event payload:

JSON
{
"event": "$pageview",
"properties": {
"distinct_id": "0190a48b-6c4e-7320-9a18-4f82c10293d1",
"$device_id": "0190a48b-6c4e-7320-9a18-4f82c10293d1",
"$is_identified": false,
"$process_person_profile": false,
"$current_url": "https://example.com/pricing"
}
}

Skipping person profiles avoids database joins and makes anonymous events up to 4x cheaper than identified events. Logged-out traffic keeps that lower rate, and PostHog bills past anonymous events as anonymous even after a visitor logs in.

  • What works without a profile. Filter by event properties like URL, referrer, and UTMs. Run web analytics, trends, funnels, SQL insights, and session replays across that anonymous distinct_id.
  • What needs a person profile. You need a profile to set person properties, build cohorts, run lifecycle insights, use group analytics, or query the persons table.
  • Changing the default. Set person_profiles to 'always' in init to create profiles for anonymous visitors too, or 'never' to disable profiles everywhere. See anonymous vs identified events.

On login: identify users

On signup or login, call identify right away with your permanent database ID. It assigns that ID, creates a person profile, and merges the browser's anonymous ID, so pre-login traffic stays attached to that user.

Web
posthog.identify(
'user_12345',
{ email: 'max@example.com' },
{ initial_plan: 'free' }
)

The second and third arguments update person properties (set on every call vs set once). For updates outside login, call setPersonProperties, or read person properties.

On logout: reset identity

When a user logs out, call reset immediately, so PostHog clears stored state and generates a new anonymous ID. Skipping this leaves later activity on that browser attached to the previous user's profile.

Web
posthog.reset()

Pass true to reset on shared kiosks or test machines to rotate the device ID as well.

Use group to tie events in the current session to a shared account, company, or workspace. Use alias only when you need to merge two separate backend IDs into one person.

Web
posthog.group('company', 'company_42', {
name: 'Acme Corp',
plan: 'enterprise',
})

See group analytics and Identity and groups for all group and identity methods.

Attach global properties

Call register or register_once to include shared metadata on every event from the current browser. These properties attach to events, including pageviews and autocaptured clicks, rather than updating the person profile.

Web
posthog.register({ app_surface: 'checkout' })
posthog.unregister('app_surface')

See Events and properties for session-scoped variants and property helpers like unregister.

Evaluate feature flags

Wait for the async fetch with onFeatureFlags, or bootstrap flags from your server so values are ready on load. If you just changed user properties, send overrides with setPersonPropertiesForFlags, so evaluation doesn't wait on server ingestion.

Web
posthog.onFeatureFlags((_flags, _variants, { errorsLoading }) => {
if (errorsLoading) return
const flag = posthog.getFeatureFlagResult('new-billing-flow')
if (flag?.enabled) {
renderFlow(flag.variant, flag.payload)
}
})

See the feature flags docs, experiments, early access feature management, and Feature flags in the reference for isFeatureEnabled, getFeatureFlagResult, reloadFeatureFlags, and updateFlags.

Run surveys

Popover surveys target and render automatically once enabled in project settings. Call getActiveMatchingSurveys and displaySurvey to wait for surveys, query matches, trigger one manually, or build your own UI:

Web
posthog.getActiveMatchingSurveys((surveys) => {
if (surveys.length > 0) {
posthog.displaySurvey(surveys[0].id)
}
})

See the surveys docs, implementing custom surveys, and Surveys in the reference.

Record sessions

Session Replay records DOM changes automatically when enabled in your project settings. Redact sensitive elements with privacy CSS classes, or control recording in code with startSessionRecording and stopSessionRecording:

Web
posthog.startSessionRecording()

See Session Replay docs, privacy controls, and Session replay in the reference.

Track errors and logs

PostHog captures unhandled browser errors automatically once enabled in project settings or initialization config. Send handled errors manually with captureException, and send structured browser logs with logger:

Web
try {
await submitOrder()
} catch (error) {
posthog.captureException(error, { step: 'payment' })
posthog.logger.error('payment_failed', {
message: error.message,
})
}

See error tracking docs, the JavaScript web logs guide, and Error tracking in the reference.

Filter events before send

Use before_send to redact sensitive parameters, sample high-volume events with sampleByEvent, or return null to drop an event before it enters the queue. You can also drop custom crawler traffic with custom_blocked_useragents.

Web
import { sampleByEvent } from 'posthog-js/customizations'
posthog.init('<ph_project_token>', {
api_host: 'https://us.i.posthog.com',
before_send: [sampleByEvent(['$autocapture'], 0.2)],
})

Debug in development

Turn on verbose SDK logging locally without changing production config. Call debug in DevTools or add ?__posthog_debug=true to your page URL:

Web
posthog.debug()

See Configuration or Version 1.x.x next.

Still have questions?

Was this page useful?