PostHog / posthog-js

Send usage data from your web app or site to PostHog, with autocapture.
https://posthog.com/docs/libraries/js
Other
278 stars 114 forks source link

Cross-domain behavior of localstorage+cookie #1399

Open dzsibi opened 3 weeks ago

dzsibi commented 3 weeks ago

Hello,

I am somewhat confused about how localstorage+cookie works across different subdomains. The current implementation merges the values stored in the cookie with those stored in local storage, preferring the values in local storage:

https://github.com/PostHog/posthog-js/blob/34204f4aff107162bdb259d2a7c855d67bf0260c/src/storage.ts#L262

But this creates a very undesirable behavior when the user navigates between different subdomains. Take the following sequence of events:

  1. User visits www.example.com, is assigned a random distinct ID, which is stored in a cookie (for .example.com) and in local storage as well (for www.example.com)
  2. User then navigates to support.example.com, where the distinct ID is loaded from the cookie (for .example.com) which is also saved to local storage there (for support.example.com).
  3. The user logs in on support.example.com, identify is called, and now has an authenticated distinct ID, which overwrites the value in the cookie (for .example.com) and in local storage (for support.example.com)
  4. The user navigates back to www.example.com, where the authenticated distinct ID is loaded from the cookie (for .example.com), but is overwritten by the anonymous distinct ID in local storage (for www.example.com). Afterwards, the anonymous distinct ID also overwrites the value in the cookie (for .example.com).
  5. (If the user then visits a third subdomain, the authenticated distinct ID is already lost.)

In most use cases, I think that if the user is identified, that information should spread across subdomains. Of course one could keep using the cookie-only storage, which solves the issue, but makes all requests to the server larger and can cause problems if the cookie grows too large (which is why I gather localstorage+cookie was made the default persistence option).

One way to fix this would be to prefer the values in the cookie, effectively reversing the merge order. Additional logic may be added to avoid merging values between different authenticated users. A conservative approach would be:

A more aggressive approach would be that always prefers the value in the cookie:

Is the current behavior by design? Would it be possible to change it / make it configurable, or should we simply roll our own PersistentStore to work around it?