-
Notifications
You must be signed in to change notification settings - Fork 237
Expand file tree
/
Copy pathposthog-core.ts
More file actions
3935 lines (3617 loc) · 143 KB
/
posthog-core.ts
File metadata and controls
3935 lines (3617 loc) · 143 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Config from './config'
import { ConsentManager, ConsentStatus } from './consent'
import {
ALIAS_ID_KEY,
COOKIELESS_MODE_FLAG_PROPERTY,
COOKIELESS_SENTINEL_VALUE,
ENABLE_PERSON_PROCESSING,
FLAG_CALL_REPORTED,
PEOPLE_DISTINCT_ID_KEY,
SURVEYS_REQUEST_TIMEOUT_MS,
USER_STATE,
} from './constants'
import { isDeadClicksEnabledForAutocapture } from './extensions/dead-clicks-autocapture'
import { setupSegmentIntegration } from './extensions/segment-integration'
import { SentryIntegration, sentryIntegration, SentryIntegrationOptions } from './extensions/sentry-integration'
import { PageViewManager } from './page-view'
import { PostHogPersistence } from './posthog-persistence'
import {
type DisplaySurveyOptions,
type SurveyCallback,
SurveyEventName,
SurveyEventProperties,
type SurveyRenderReason,
} from './posthog-surveys-types'
import { ProductTourEventName, ProductTourEventProperties } from './posthog-product-tours-types'
import { RateLimiter } from './rate-limiter'
import { RemoteConfigLoader } from './remote-config'
import { extendURLParams, request, SUPPORTS_REQUEST } from './request'
import { DEFAULT_FLUSH_INTERVAL_MS, RequestQueue } from './request-queue'
import { RetryQueue } from './retry-queue'
import { ScrollManager } from './scroll-manager'
import { SessionPropsManager } from './session-props'
import { SessionIdManager } from './sessionid'
import { localStore } from './storage'
import {
CaptureOptions,
CaptureResult,
Compression,
ConfigDefaults,
EarlyAccessFeatureCallback,
EarlyAccessFeatureStage,
EventName,
ExceptionAutoCaptureConfig,
FeatureFlagsCallback,
FeatureFlagOptions,
FeatureFlagResult,
JsonType,
OverrideConfig,
PostHogConfig,
Properties,
Property,
QueuedRequestWithOptions,
RemoteConfig,
RequestCallback,
SessionIdChangedCallback,
SnippetArrayItem,
ToolbarParams,
PostHogInterface,
} from './types'
import type { TreeShakeable } from '@posthog/types'
import {
_copyAndTruncateStrings,
addEventListener,
each,
eachArray,
extend,
isCrossDomainCookie,
migrateConfigField,
PostHogConfigError,
safewrapClass,
} from './utils'
import { isLikelyBot } from './utils/blocked-uas'
import { getEventProperties } from './utils/event-utils'
import { assignableWindow, document, location, navigator, userAgent, window } from './utils/globals'
import { logger } from './utils/logger'
import { getPersonPropertiesHash } from './utils/property-utils'
import { RequestRouter, RequestRouterRegion } from './utils/request-router'
import { SimpleEventEmitter } from './utils/simple-event-emitter'
import {
DEFAULT_DISPLAY_SURVEY_OPTIONS,
getSurveyInteractionProperty,
setSurveySeenOnLocalStorage,
} from './utils/survey-utils'
import {
isEmptyString,
isFunction,
isKnownUnsafeEditableEvent,
isNullish,
isNumber,
isString,
isUndefined,
includes,
isDistinctIdStringLike,
isArray,
isEmptyObject,
isObject,
isBoolean,
} from '@posthog/core'
import { uuidv7 } from './uuidv7'
import { ExternalIntegrations } from './extensions/external-integration'
import type { PostHogSurveys } from './posthog-surveys'
import type { Autocapture } from './autocapture'
import type { DeadClicksAutocapture } from './extensions/dead-clicks-autocapture'
import type { ExceptionObserver } from './extensions/exception-autocapture'
import type { HistoryAutocapture } from './extensions/history-autocapture'
import type { WebVitalsAutocapture } from './extensions/web-vitals'
import type { Heatmaps } from './heatmaps'
import type { PostHogConversations } from './extensions/conversations/posthog-conversations'
import type { PostHogExceptions } from './posthog-exceptions'
import type { PostHogLogs } from './posthog-logs'
import type { PostHogProductTours } from './posthog-product-tours'
import type { SiteApps } from './site-apps'
import type { SessionRecording } from './extensions/replay/session-recording'
import type { Extension } from './extensions/types'
import type { Toolbar } from './extensions/toolbar'
import type { PostHogFeatureFlags } from './posthog-featureflags'
import type { WebExperiments } from './web-experiments'
/*
SIMPLE STYLE GUIDE:
Use TypeScript accessibility modifiers, e.g. private/protected
If something is not part of the public interface:
* prefix it with _ to allow mangling
* prefix it with __ to disable mangling, but signal that it is internal
Globals should be all caps
*/
/* posthog.init is called with `Partial<PostHogConfig>`
* and we want to ensure that only valid keys are passed to the config object.
* TypeScript does not enforce that the object passed does not have extra keys.
* So someone can call with { bootstrap: { distinctId: '123'} }
* which is not a valid key. They should have passed distinctID (upper case D).
* That's a really tricky mistake to spot.
* The OnlyValidKeys type ensures that only keys that are valid in the PostHogConfig type are allowed.
*/
type OnlyValidKeys<T, Shape> = T extends Shape ? (Exclude<keyof T, keyof Shape> extends never ? T : never) : never
const instances: Record<string, PostHog> = {}
// Tracks re-entrant calls to _execute_array. Used to detect when a third-party
// Proxy (e.g., TikTok's in-app browser) wraps window.posthog and converts method
// calls into push() calls, which would otherwise cause infinite recursion.
let _executeArrayDepth = 0
const __NOOP = () => {}
const PRIMARY_INSTANCE_NAME = 'posthog'
/*
* Dynamic... constants? Is that an oxymoron?
*/
// http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/
// https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#withCredentials
// IE<10 does not support cross-origin XHR's but script tags
// with defer won't block window.onload; ENQUEUE_REQUESTS
// should only be true for Opera<12
let ENQUEUE_REQUESTS = !SUPPORTS_REQUEST && userAgent?.indexOf('MSIE') === -1 && userAgent?.indexOf('Mozilla') === -1
const defaultsThatVaryByConfig = (
defaults?: ConfigDefaults
): Pick<
PostHogConfig,
| 'rageclick'
| 'capture_pageview'
| 'session_recording'
| 'external_scripts_inject_target'
| 'internal_or_test_user_hostname'
| 'strict_identify'
> => ({
rageclick: defaults && defaults >= '2025-11-30' ? { content_ignorelist: true } : true,
capture_pageview: defaults && defaults >= '2025-05-24' ? 'history_change' : true,
session_recording: defaults && defaults >= '2025-11-30' ? { strictMinimumDuration: true } : {},
external_scripts_inject_target: defaults && defaults >= '2026-01-30' ? 'head' : 'body',
internal_or_test_user_hostname: defaults && defaults >= '2026-01-30' ? /^(localhost|127\.0\.0\.1)$/ : undefined,
strict_identify: defaults && defaults >= '2026-04-01' ? true : false,
})
// NOTE: Remember to update `types.ts` when changing a default value
// to guarantee documentation is up to date, make sure to also update our website docs
// NOTE²: This shouldn't ever change because we try very hard to be backwards-compatible
export const defaultConfig = (defaults?: ConfigDefaults): PostHogConfig => ({
api_host: 'https://us.i.posthog.com',
flags_api_host: null,
ui_host: null,
token: '',
autocapture: true,
cross_subdomain_cookie: isCrossDomainCookie(document?.location),
persistence: 'localStorage+cookie', // up to 1.92.0 this was 'cookie'. It's easy to migrate as 'localStorage+cookie' will migrate data from cookie storage
persistence_name: '',
cookie_persisted_properties: [],
loaded: __NOOP,
save_campaign_params: true,
custom_campaign_params: [],
custom_blocked_useragents: [],
save_referrer: true,
capture_pageleave: 'if_capture_pageview', // We'll only capture pageleave events if capture_pageview is also true
defaults: defaults ?? 'unset',
__preview_deferred_init_extensions: false, // Opt-in only for now
debug: (location && isString(location?.search) && location.search.indexOf('__posthog_debug=true') !== -1) || false,
cookie_expiration: 365,
upgrade: false,
disable_session_recording: false,
disable_persistence: false,
disable_web_experiments: true, // disabled in beta.
disable_surveys: false,
disable_surveys_automatic_display: false,
disable_conversations: false,
disable_product_tours: false,
disable_external_dependency_loading: false,
enable_recording_console_log: undefined, // When undefined, it falls back to the server-side setting
secure_cookie: window?.location?.protocol === 'https:',
ip: false,
opt_out_capturing_by_default: false,
opt_out_persistence_by_default: false,
opt_out_useragent_filter: false,
opt_out_capturing_persistence_type: 'localStorage',
consent_persistence_name: null,
opt_out_capturing_cookie_prefix: null,
opt_in_site_apps: false,
property_denylist: [],
respect_dnt: false,
sanitize_properties: null,
request_headers: {}, // { header: value, header2: value }
request_batching: true,
properties_string_max_length: 65535,
mask_all_element_attributes: false,
mask_all_text: false,
mask_personal_data_properties: false,
custom_personal_data_properties: [],
advanced_disable_flags: false,
advanced_disable_decide: false,
advanced_disable_feature_flags: false,
advanced_disable_feature_flags_on_first_load: false,
advanced_only_evaluate_survey_feature_flags: false,
advanced_feature_flags_dedup_per_session: false,
advanced_enable_surveys: false,
advanced_disable_toolbar_metrics: false,
feature_flag_request_timeout_ms: 3000,
surveys_request_timeout_ms: SURVEYS_REQUEST_TIMEOUT_MS,
on_request_error: (res) => {
const error = 'Bad HTTP status: ' + res.statusCode + ' ' + res.text
logger.error(error)
},
get_device_id: (uuid) => uuid,
capture_performance: undefined,
name: 'posthog',
bootstrap: {},
disable_compression: false,
session_idle_timeout_seconds: 30 * 60, // 30 minutes
person_profiles: 'identified_only',
before_send: undefined,
request_queue_config: { flush_interval_ms: DEFAULT_FLUSH_INTERVAL_MS },
error_tracking: {},
// Used for internal testing
_onCapture: __NOOP,
// make the default be lazy loading replay
__preview_eager_load_replay: false,
...defaultsThatVaryByConfig(defaults),
})
export const configRenames = (origConfig: Partial<PostHogConfig>): Partial<PostHogConfig> => {
const renames: Partial<PostHogConfig> = {}
if (!isUndefined(origConfig.process_person)) {
renames.person_profiles = origConfig.process_person
}
if (!isUndefined(origConfig.xhr_headers)) {
renames.request_headers = origConfig.xhr_headers
}
if (!isUndefined(origConfig.cookie_name)) {
renames.persistence_name = origConfig.cookie_name
}
if (!isUndefined(origConfig.disable_cookie)) {
renames.disable_persistence = origConfig.disable_cookie
}
if (!isUndefined(origConfig.store_google)) {
renames.save_campaign_params = origConfig.store_google
}
if (!isUndefined(origConfig.verbose)) {
renames.debug = origConfig.verbose
}
// on_xhr_error is not present, as the type is different to on_request_error
// the original config takes priority over the renames
const newConfig = extend({}, renames, origConfig)
// merge property_blacklist into property_denylist
if (isArray(origConfig.property_blacklist)) {
if (isUndefined(origConfig.property_denylist)) {
newConfig.property_denylist = origConfig.property_blacklist
} else if (isArray(origConfig.property_denylist)) {
newConfig.property_denylist = [...origConfig.property_blacklist, ...origConfig.property_denylist]
} else {
logger.error('Invalid value for property_denylist config: ' + origConfig.property_denylist)
}
}
return newConfig
}
class DeprecatedWebPerformanceObserver {
get _forceAllowLocalhost(): boolean {
return this.__forceAllowLocalhost
}
set _forceAllowLocalhost(value: boolean) {
logger.error(
'WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`'
)
this.__forceAllowLocalhost = value
}
private __forceAllowLocalhost: boolean = false
}
/**
*
* This is the SDK reference for the PostHog JavaScript Web SDK.
* You can learn more about example usage in the
* [JavaScript Web SDK documentation](/docs/libraries/js).
* You can also follow [framework specific guides](/docs/frameworks)
* to integrate PostHog into your project.
*
* This SDK is designed for browser environments.
* Use the PostHog [Node.js SDK](/docs/libraries/node) for server-side usage.
*
* @constructor
*/
export class PostHog implements PostHogInterface {
static __defaultExtensionClasses: PostHogConfig['__extensionClasses'] = {}
__loaded: boolean
config: PostHogConfig
_originalUserConfig?: Partial<PostHogConfig>
rateLimiter: RateLimiter
scrollManager: ScrollManager
pageViewManager: PageViewManager
featureFlags: TreeShakeable<PostHogFeatureFlags>
surveys: TreeShakeable<PostHogSurveys>
conversations: TreeShakeable<PostHogConversations>
logs: TreeShakeable<PostHogLogs>
experiments: TreeShakeable<WebExperiments>
toolbar: TreeShakeable<Toolbar>
exceptions: TreeShakeable<PostHogExceptions>
consent: ConsentManager
// These are instance-specific state created after initialisation
persistence?: PostHogPersistence
sessionPersistence?: PostHogPersistence
sessionManager?: SessionIdManager
sessionPropsManager?: SessionPropsManager
requestRouter: RequestRouter
siteApps?: SiteApps
autocapture?: Autocapture
heatmaps?: Heatmaps
webVitalsAutocapture?: WebVitalsAutocapture
exceptionObserver?: ExceptionObserver
deadClicksAutocapture?: DeadClicksAutocapture
historyAutocapture?: HistoryAutocapture
productTours?: PostHogProductTours
_requestQueue?: RequestQueue
_retryQueue?: RetryQueue
sessionRecording?: SessionRecording
externalIntegrations?: ExternalIntegrations
webPerformance = new DeprecatedWebPerformanceObserver()
_initialPageviewCaptured: boolean
_visibilityStateListener: (() => void) | null
_personProcessingSetOncePropertiesSent: boolean = false
_triggered_notifs: any
compression?: Compression
__request_queue: QueuedRequestWithOptions[]
_pendingRemoteConfig?: RemoteConfig
_remoteConfigLoader?: RemoteConfigLoader
analyticsDefaultEndpoint: string
version: string = Config.LIB_VERSION
_initialPersonProfilesConfig: 'always' | 'never' | 'identified_only' | null
_cachedPersonProperties: string | null
SentryIntegration: typeof SentryIntegration
sentryIntegration: (options?: SentryIntegrationOptions) => ReturnType<typeof sentryIntegration>
_internalEventEmitter = new SimpleEventEmitter()
private readonly _extensions: Extension[] = []
private _replaceExtension<T extends Extension>(oldExt: T | undefined, newExt: T): T {
if (oldExt) {
const idx = this._extensions.indexOf(oldExt)
if (idx !== -1) {
this._extensions.splice(idx, 1)
}
}
this._extensions.push(newExt)
newExt.initialize?.()
return newExt
}
// Legacy property to support existing usage - this isn't technically correct but it's what it has always been - a proxy for flags being loaded
/** @deprecated Use `flagsEndpointWasHit` instead. We migrated to using a new feature flag endpoint and the new method is more semantically accurate */
public get decideEndpointWasHit(): boolean {
return this.featureFlags?.hasLoadedFlags ?? false
}
public get flagsEndpointWasHit(): boolean {
return this.featureFlags?.hasLoadedFlags ?? false
}
/** DEPRECATED: We keep this to support existing usage but now one should just call .setPersonProperties */
people: {
set: (prop: string | Properties, to?: string, callback?: RequestCallback) => void
set_once: (prop: string | Properties, to?: string, callback?: RequestCallback) => void
}
constructor() {
this.config = defaultConfig()
this.SentryIntegration = SentryIntegration
this.sentryIntegration = (options?: SentryIntegrationOptions) => sentryIntegration(this, options)
this.__request_queue = []
this.__loaded = false
this.analyticsDefaultEndpoint = '/e/'
this._initialPageviewCaptured = false
this._visibilityStateListener = null
this._initialPersonProfilesConfig = null
this._cachedPersonProperties = null
this.scrollManager = new ScrollManager(this)
this.pageViewManager = new PageViewManager(this)
this.rateLimiter = new RateLimiter(this)
this.requestRouter = new RequestRouter(this)
this.consent = new ConsentManager(this)
this.externalIntegrations = new ExternalIntegrations(this)
// Eagerly construct extensions from default classes so they're available before init().
// For the slim bundle, these remain undefined until _initExtensions sets them from config.
const ext = PostHog.__defaultExtensionClasses ?? {}
this.featureFlags = ext.featureFlags && new ext.featureFlags(this)
this.toolbar = ext.toolbar && new ext.toolbar(this)
this.surveys = ext.surveys && new ext.surveys(this)
this.conversations = ext.conversations && new ext.conversations(this)
this.logs = ext.logs && new ext.logs(this)
this.experiments = ext.experiments && new ext.experiments(this)
this.exceptions = ext.exceptions && new ext.exceptions(this)
// NOTE: See the property definition for deprecation notice
this.people = {
set: (prop: string | Properties, to?: string, callback?: RequestCallback) => {
const setProps = isString(prop) ? { [prop]: to } : prop
this.setPersonProperties(setProps)
callback?.({} as any)
},
set_once: (prop: string | Properties, to?: string, callback?: RequestCallback) => {
const setProps = isString(prop) ? { [prop]: to } : prop
this.setPersonProperties(undefined, setProps)
callback?.({} as any)
},
}
this.on('eventCaptured', (data) => logger.info(`send "${data?.event}"`, data))
}
// Initialization methods
/**
* Initializes a new instance of the PostHog capturing object.
*
* @remarks
* 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](https://github.com/posthog/posthog-js/blob/6e0e873/src/posthog-core.js#L57-L91)
*
* @example
* ```js
* // basic initialization
* posthog.init('<ph_project_api_key>', {
* api_host: '<ph_client_api_host>'
* })
* ```
*
* @example
* ```js
* // multiple instances
* posthog.init('<ph_project_api_key>', {}, 'project1')
* posthog.init('<ph_project_api_key>', {}, 'project2')
* ```
*
* @public
*
* @param token - Your PostHog API token
* @param config - A dictionary of config options to override
* @param name - The name for the new posthog instance that you want created
*
* {@label Initialization}
*
* @returns The newly initialized PostHog instance
*/
init(
token: string,
config?: OnlyValidKeys<Partial<PostHogConfig>, Partial<PostHogConfig>>,
name?: string
): PostHog {
if (!name || name === PRIMARY_INSTANCE_NAME) {
// This means we are initializing the primary instance (i.e. this)
return this._init(token, config, name)
} else {
const namedPosthog = instances[name] ?? new PostHog()
namedPosthog._init(token, config, name)
instances[name] = namedPosthog
// Add as a property to the primary instance (this isn't type-safe but it is how it was always done)
;(instances[PRIMARY_INSTANCE_NAME] as any)[name] = namedPosthog
return namedPosthog
}
}
// posthog._init(token:string, config:object, name:string)
//
// This function sets up the current instance of the posthog
// library. The difference between this method and the init(...)
// method is this one initializes the actual instance, whereas the
// init(...) method sets up a new library and calls _init on it.
//
// Note that there are operations that can be asynchronous, so we
// accept a callback that is called when all the asynchronous work
// is done. Note that we do not use promises because we want to be
// IE11 compatible. We could use polyfills, which would make the
// code a bit cleaner, but will add some overhead.
//
_init(token: string, config: Partial<PostHogConfig> = {}, name?: string): PostHog {
if (isUndefined(token) || isEmptyString(token)) {
logger.critical(
'PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()'
)
return this
}
if (this.__loaded) {
// need to be able to log before having processed debug config
// eslint-disable-next-line no-console
console.warn('[PostHog.js]', 'You have already initialized PostHog! Re-initializing is a no-op')
return this
}
this.__loaded = true
this.config = {} as PostHogConfig // will be set right below
config.debug = this._checkLocalStorageForDebug(config.debug)
this._originalUserConfig = config // Store original user config for migration
this._triggered_notifs = []
if (config.person_profiles) {
this._initialPersonProfilesConfig = config.person_profiles
} else if (config.process_person) {
this._initialPersonProfilesConfig = config.process_person
}
this.set_config(
extend({}, defaultConfig(config.defaults), configRenames(config), {
name: name,
token: token,
})
)
if (this.config.on_xhr_error) {
logger.error('on_xhr_error is deprecated. Use on_request_error instead')
}
this.compression = config.disable_compression ? undefined : Compression.GZipJS
const persistenceDisabled = this._is_persistence_disabled()
this.persistence = new PostHogPersistence(this.config, persistenceDisabled)
this.sessionPersistence =
this.config.persistence === 'sessionStorage' || this.config.persistence === 'memory'
? this.persistence
: new PostHogPersistence({ ...this.config, persistence: 'sessionStorage' }, persistenceDisabled)
// should I store the initial person profiles config in persistence?
const initialPersistenceProps = { ...this.persistence.props }
const initialSessionProps = { ...this.sessionPersistence.props }
this.register({ $initialization_time: new Date().toISOString() })
this._requestQueue = new RequestQueue(
(req) => this._send_retriable_request(req),
this.config.request_queue_config
)
this._retryQueue = new RetryQueue(this)
this.__request_queue = []
const startInCookielessMode =
this.config.cookieless_mode === 'always' ||
(this.config.cookieless_mode === 'on_reject' && this.consent.isExplicitlyOptedOut())
if (!startInCookielessMode) {
this.sessionManager = new SessionIdManager(this)
this.sessionPropsManager = new SessionPropsManager(this, this.sessionManager, this.persistence)
}
// Conditionally defer extension initialization based on config
if (this.config.__preview_deferred_init_extensions) {
// EXPERIMENTAL: Defer non-critical extension initialization to next tick
// This reduces main thread blocking during init
// while keeping critical path (persistence, sessions, capture) synchronous
logger.info('Deferring extension initialization to improve startup performance')
setTimeout(() => {
this._initExtensions(startInCookielessMode)
}, 0)
} else {
// Legacy synchronous initialization (default for now)
logger.info('Initializing extensions synchronously')
this._initExtensions(startInCookielessMode)
}
// if any instance on the page has debug = true, we set the
// global debug to be true
Config.DEBUG = Config.DEBUG || this.config.debug
if (Config.DEBUG) {
logger.info('Starting in debug mode', {
this: this,
config,
thisC: { ...this.config },
p: initialPersistenceProps,
s: initialSessionProps,
})
}
// isUndefined doesn't provide typehint here so wouldn't reduce bundle as we'd need to assign
// eslint-disable-next-line posthog-js/no-direct-undefined-check
if (config.bootstrap?.distinctID !== undefined) {
const bootstrapDistinctId = config.bootstrap.distinctID
const existingDistinctId = this.get_distinct_id()
const existingUserState = this.persistence.get_property(USER_STATE)
if (
config.bootstrap.isIdentifiedID &&
existingDistinctId != null &&
existingDistinctId !== bootstrapDistinctId &&
existingUserState === 'anonymous'
) {
// The server bootstrapped identity for an identified user, but local persistence
// still has an anonymous ID from a previous session. Calling identify() merges
// the anonymous user into the identified user, ensuring consistent identity
// for feature flag evaluation and preventing duplicate $feature_flag_called events.
//
// Note: this runs during _init(), before _loaded() enables the request queue.
// The $identify event is enqueued and flushed once the queue starts. The
// reloadFeatureFlags() call inside identify() sets _reloadDebouncer, so the
// subsequent ensureFlagsLoaded() from _onRemoteConfig is a no-op (no double request).
this.identify(bootstrapDistinctId)
} else if (
config.bootstrap.isIdentifiedID &&
existingDistinctId != null &&
existingDistinctId !== bootstrapDistinctId &&
existingUserState === 'identified'
) {
// The existing user is already identified with a different ID. Silently
// switching identities without an $identify event would corrupt analytics.
// Preserve the existing identity and log a warning.
logger.warn(
'Bootstrap distinctID differs from an already-identified user. ' +
'The existing identity is preserved. Call reset() before reinitializing ' +
'if you intend to switch users.'
)
} else {
const uuid = this.config.get_device_id(uuidv7())
const deviceID = config.bootstrap.isIdentifiedID ? uuid : bootstrapDistinctId
this.persistence.set_property(USER_STATE, config.bootstrap.isIdentifiedID ? 'identified' : 'anonymous')
this.register({
distinct_id: bootstrapDistinctId,
$device_id: deviceID,
})
}
}
if (startInCookielessMode) {
this.register_once(
{
distinct_id: COOKIELESS_SENTINEL_VALUE,
$device_id: null,
},
''
)
} else if (!this.get_distinct_id()) {
// There is no need to set the distinct id
// or the device id if something was already stored
// in the persistence
const uuid = this.config.get_device_id(uuidv7())
this.register_once(
{
distinct_id: uuid,
$device_id: uuid,
},
''
)
// distinct id == $device_id is a proxy for anonymous user
this.persistence.set_property(USER_STATE, 'anonymous')
}
// Set up event handler for pageleave
// Use `onpagehide` if available, see https://calendar.perfplanet.com/2020/beaconing-in-practice/#beaconing-reliability-avoiding-abandons
//
// Not making it passive to try and force the browser to handle this before the page is unloaded
addEventListener(window, 'onpagehide' in self ? 'pagehide' : 'unload', this._handle_unload.bind(this), {
passive: false,
})
// We want to avoid promises for IE11 compatibility, so we use callbacks here
if (config.segment) {
setupSegmentIntegration(this, () => this._loaded())
} else {
this._loaded()
}
if (isFunction(this.config._onCapture) && this.config._onCapture !== __NOOP) {
logger.warn('onCapture is deprecated. Please use `before_send` instead')
this.on('eventCaptured', (data) => this.config._onCapture(data.event, data))
}
if (this.config.ip) {
logger.warn(
'The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'
)
}
return this
}
private _initExtensions(startInCookielessMode: boolean): void {
// we don't support IE11 anymore, so performance.now is safe
// eslint-disable-next-line compat/compat
const initStartTime = performance.now()
const ext = { ...PostHog.__defaultExtensionClasses, ...this.config.__extensionClasses }
const initTasks: Array<() => void> = []
// Due to name mangling, we can't easily iterate and assign these extensions
// The assignment needs to also be mangled. Thus, the loop is unrolled.
if (ext.featureFlags) {
this._extensions.push((this.featureFlags = this.featureFlags ?? new ext.featureFlags(this)))
}
if (ext.exceptions) {
this._extensions.push((this.exceptions = this.exceptions ?? new ext.exceptions(this)))
}
if (ext.historyAutocapture) {
this._extensions.push((this.historyAutocapture = new ext.historyAutocapture(this)))
}
if (ext.tracingHeaders) {
this._extensions.push(new ext.tracingHeaders(this))
}
if (ext.siteApps) {
this._extensions.push((this.siteApps = new ext.siteApps(this)))
}
if (ext.sessionRecording && !startInCookielessMode) {
this._extensions.push((this.sessionRecording = new ext.sessionRecording(this)))
}
if (!this.config.disable_scroll_properties) {
initTasks.push(() => {
this.scrollManager.startMeasuringScrollPosition()
})
}
if (ext.autocapture) {
this._extensions.push((this.autocapture = new ext.autocapture(this)))
}
if (ext.surveys) {
this._extensions.push((this.surveys = this.surveys ?? new ext.surveys(this)))
}
if (ext.logs) {
this._extensions.push((this.logs = this.logs ?? new ext.logs(this)))
}
if (ext.conversations) {
this._extensions.push((this.conversations = this.conversations ?? new ext.conversations(this)))
}
if (ext.productTours) {
this._extensions.push((this.productTours = new ext.productTours(this)))
}
if (ext.heatmaps) {
this._extensions.push((this.heatmaps = new ext.heatmaps(this)))
}
if (ext.webVitalsAutocapture) {
this._extensions.push((this.webVitalsAutocapture = new ext.webVitalsAutocapture(this)))
}
if (ext.exceptionObserver) {
this._extensions.push((this.exceptionObserver = new ext.exceptionObserver(this)))
}
if (ext.deadClicksAutocapture) {
this._extensions.push(
(this.deadClicksAutocapture = new ext.deadClicksAutocapture(this, isDeadClicksEnabledForAutocapture))
)
}
if (ext.toolbar) {
this._extensions.push((this.toolbar = this.toolbar ?? new ext.toolbar(this)))
}
if (ext.experiments) {
this._extensions.push((this.experiments = this.experiments ?? new ext.experiments(this)))
}
this._extensions.forEach((extension) => {
if (!extension.initialize) return
initTasks.push(() => {
extension.initialize?.()
})
})
// Replay any pending remote config that arrived before extensions were ready
initTasks.push(() => {
if (this._pendingRemoteConfig) {
const config = this._pendingRemoteConfig
this._pendingRemoteConfig = undefined // Clear before replaying to avoid re-storing
this._onRemoteConfig(config)
}
})
// Process tasks with time-slicing to avoid blocking
this._processInitTaskQueue(initTasks, initStartTime)
}
private _processInitTaskQueue(queue: Array<() => void>, initStartTime: number): void {
const TIME_BUDGET_MS = 30 // Respect frame budget (~60fps = 16ms, but we're already deferred)
while (queue.length > 0) {
// Only time-slice if deferred init is enabled, otherwise run synchronously
if (this.config.__preview_deferred_init_extensions) {
// we don't support IE11 anymore, so performance.now is safe
// eslint-disable-next-line compat/compat
const elapsed = performance.now() - initStartTime
// Check if we've exceeded our time budget
if (elapsed >= TIME_BUDGET_MS && queue.length > 0) {
// Yield to browser, then continue processing
setTimeout(() => {
this._processInitTaskQueue(queue, initStartTime)
}, 0)
return
}
}
// Process next task
const task = queue.shift()
if (task) {
try {
task()
} catch (error) {
logger.error('Error initializing extension:', error)
}
}
}
// All tasks complete - record timing for both sync and deferred modes
// we don't support IE11 anymore, so performance.now is safe
// eslint-disable-next-line compat/compat
const taskInitTiming = Math.round(performance.now() - initStartTime)
this.register_for_session({
$sdk_debug_extensions_init_method: this.config.__preview_deferred_init_extensions
? 'deferred'
: 'synchronous',
$sdk_debug_extensions_init_time_ms: taskInitTiming,
})
if (this.config.__preview_deferred_init_extensions) {
logger.info(`PostHog extensions initialized (${taskInitTiming}ms)`)
}
}
_onRemoteConfig(config: RemoteConfig) {
if (!(document && document.body)) {
logger.info('document not ready yet, trying again in 500 milliseconds...')
setTimeout(() => {
this._onRemoteConfig(config)
}, 500)
return
}
// Store config in case extensions aren't initialized yet (only needed for deferred init)
if (this.config.__preview_deferred_init_extensions) {
this._pendingRemoteConfig = config
}
this.compression = undefined
if (config.supportedCompression && !this.config.disable_compression) {
this.compression = includes(config['supportedCompression'], Compression.GZipJS)
? Compression.GZipJS
: includes(config['supportedCompression'], Compression.Base64)
? Compression.Base64
: undefined
}
if (config.analytics?.endpoint) {
this.analyticsDefaultEndpoint = config.analytics.endpoint
}
this.set_config({
person_profiles: this._initialPersonProfilesConfig ? this._initialPersonProfilesConfig : 'identified_only',
})
this._extensions.forEach((ext) => ext.onRemoteConfig?.(config))
}
_loaded(): void {
try {
this.config.loaded(this)
} catch (err) {
logger.critical('`loaded` function failed', err)
}
this._start_queue_if_opted_in()
// Check if current hostname matches internal_or_test_user_hostname pattern and mark as test user before any events
if (this.config.internal_or_test_user_hostname && location?.hostname) {
const hostname = location.hostname
const pattern = this.config.internal_or_test_user_hostname
const matches = typeof pattern === 'string' ? hostname === pattern : pattern.test(hostname)
if (matches) {
this.setInternalOrTestUser()
}
}
// this happens after "loaded" so a user can call identify or any other things before the pageview fires
if (this.config.capture_pageview) {
// NOTE: We want to fire this on the next tick as the previous implementation had this side effect
// and some clients may rely on it
setTimeout(() => {
if (this.consent.isOptedIn() || this.config.cookieless_mode === 'always') {
this._captureInitialPageview()
}
}, 1)
}
this._remoteConfigLoader = new RemoteConfigLoader(this)
this._remoteConfigLoader.load()
}
_start_queue_if_opted_in(): void {
if (this.is_capturing()) {
if (this.config.request_batching) {
this._requestQueue?.enable()
}
}
}
_dom_loaded(): void {
if (this.is_capturing()) {
eachArray(this.__request_queue, (item) => this._send_retriable_request(item))
}
this.__request_queue = []
this._start_queue_if_opted_in()
}
_handle_unload(): void {
this.surveys?.handlePageUnload()
if (!this.config.request_batching) {
if (this._shouldCapturePageleave()) {
this.capture('$pageleave', null, { transport: 'sendBeacon' })
}
return
}
if (this._shouldCapturePageleave()) {
this.capture('$pageleave')
}
this._requestQueue?.unload()
this._retryQueue?.unload()
}
_send_request(options: QueuedRequestWithOptions): void {
if (!this.__loaded) {
return
}
if (ENQUEUE_REQUESTS) {
this.__request_queue.push(options)
return
}
if (this.rateLimiter.isServerRateLimited(options.batchKey)) {
return
}
options.transport = options.transport || this.config.api_transport
options.url = extendURLParams(options.url, {
// Whether to detect ip info or not
ip: this.config.ip ? 1 : 0,
})
options.headers = {
...this.config.request_headers,
...options.headers,
}
options.compression = options.compression === 'best-available' ? this.compression : options.compression
options.disableXHRCredentials = this.config.__preview_disable_xhr_credentials
if (this.config.__preview_disable_beacon) {
options.disableTransport = ['sendBeacon']