segmentio / analytics.js-core

The hassle-free way to integrate analytics into any web application.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

No way to determine if anonymousID is set without setting it

lewish opened this issue · comments

We've recently moved to a server-side rendering setup, and as part of that we are also starting to run rendering experiments.

This requires our server to know the anonymous ID server-side, as we will use this as the input into the experiment switching logic. This is all well and good when the user has visited our site before, as on the server we can read the ajs_anoymous_id cookie.

However, when this is the users first visit to our site, OR when it is the first visit to a subdomain on our site, we don't know the anonymous ID server-side as there are no cookies yet, so we make one up, hoping to set it as a permanent ID client-side, but also accepting that once the client code runs, it may be overriden by analytics.js.

In this case we would like to:

  • Have the server decide an anonymous ID for the user and use this for SSR experiment rendering
  • Send it back with the initial page response
  • Before the analytics.js load call is made, check to see if analytics.js actually does have a known anonymous ID (from another domain, cookie, or localStorage) *
  • If it does not, then we want to call analytics.setAnonymousId(ourServerGeneratedAnonId)
  • If it does, then we will leave it as is, and accept that our SSR used an incorrect anonymous ID for rendering (hopefully rare)

I have all this wired up, except * - as calling analytics.load immediately sets the anonymous ID if it doesn't exist, so I can't tell when to override or not without manually looking at localStorage, cookies, and trying to re-create the logic inside analytics.js code.

Proposal

I would like to add a public API to analytics.js that can return the currently known anonymous ID without setting it to a new UUID if it doesn't exist, or a way to set the anonymous ID only if it doesn't already exist.

This would enable a few things, not only server side-experiments, but also server side tracks and pages that use the same anonymous ID as the client.

I'm happy to send a PR if there is agreement, or if there are any suggestions for workarounds, I'm all ears!

commented

This issue has been automatically marked stale because it has not had any activity in the last 60 days. If no further activity occurs within 7 days, it will be closed. Closed does not mean "never", just that it has no momentum to get accomplished any time soon. See CONTRIBUTING.md for more info.

commented

Closing due to staleness. Closed does not mean "never", just that it has no momentum to get accomplished any time soon. See CONTRIBUTING.md for more info.