amplitude / Amplitude-TypeScript

TypeScript Amplitude Analytics SDK
https://amplitude.github.io/Amplitude-TypeScript/
MIT License
142 stars 40 forks source link

TypeScript SDK causes errors when user browses in Incognito mode #167

Closed agatalisowskaCC closed 2 years ago

agatalisowskaCC commented 2 years ago

Code examples:

import { init } from '@amplitude/analytics-browser'
init(process.env.AMPLITUDE_TOKEN, null, {
  serverZone: ServerZone.EU,
})
import {
  setOptOut,
  Identify,
  identify,
  setUserId,
} from '@amplitude/analytics-browser'

if (isUserInternal(ua)) {
// Opt-out internal users from Amplitude tracking
  setOptOut(true)
} else {
  const userIdentify = new Identify()
  setUserId(ua?.id)
  userIdentify.set('userName', ua?.name)
  userIdentify.set('userEmail', ua?.username)
  identify(userIdentify)
}

Expected Behavior

I'm aware that Amplitude & other analytics tools can be blocked in the browser's Incognito mode and by script blocking tools. However, I would expect Amplitude to not track the user in this case, not to throw errors and crash my application.

Current Behavior

In browser incognito mode, Amplitude is probably blocked. init method seems to work ok (doesn't throw any errors), but then when executing setOptOut or setUserId methods, user gets the following errors:

TypeError: Cannot set properties of undefined (setting 'optOut')
at AmplitudeBrowser.setOptOut
TypeError: Cannot set properties of undefined (setting 'userId')
at AmplitudeBrowser.setUserId

Possible Solution

This problem doesn't exist in JavaScript SDK. I needed to switch back to using JavaScript SDK (which is marked as legacy now) to solve this problem.

I suppose this problem could be caused by a lack of instance object in TypeScript SDK. There is no amplitude object to check if it exists and no getInstance method. Maybe merging this pull request could be helpful: https://github.com/amplitude/Amplitude-TypeScript/pull/106

Maybe a method to check if Amplitude is initialized could solve this problem: https://github.com/amplitude/Amplitude-TypeScript/issues/169

Steps to Reproduce

  1. Initialize Amplitude TypeScript SDK
  2. Use setOptOut or setUserId methods
  3. Run application in browser incognito mode

Environment

liuyang1520 commented 2 years ago

@kevinpagtakhan , are you working on this issue? If not, I will take a look. Thanks!