analytics-next icon indicating copy to clipboard operation
analytics-next copied to clipboard

Support for multiple write keys.

Open BorePlusPlus opened this issue 3 years ago • 1 comments

Hello,

We were led to believe that it is possible to run two instances of analytics-next with different write keys side by side. One via segment source snippet (exposed on window.analytics) and the other one as an npm module.

When we try to do this, it mostly works with one quirk/bug. If the two instances are loading concurrently (which is the common scenario), it can happen that events fired via window.analytics (segment source snippet) cause two network requests - one using the segment source snippet write key and the other one using npm module's source key. Once both instances are finished loading they behave as expected with each only firing network requests for its own events.

We were speculating that this is due to the fact that window.analytics as provided by snippet creates a queueing implementation of methods (to be used before the analytics-next is fully loaded) and then somehow snippet and npm module versions both read and fire events on that queue. Not sure if this is actually the case - it's just a guess.

I assembled a small sample application that demonstrates the issue. It loads analytics-next from both snippet and npm module, but only fires a page event on the snippet version. If you reload the page several times, you should see examples of that single page event causing two requests to be sent to a p endpoint. See: Two requests to p

You will of course need to provide your own write keys here and here.

Using multiple instances of analytics with different write keys seems to have been something that was "advertised" as a feature, and when talking to our Segment representative they said that this should be possible with analytics-next as well.

Thanks for any help or further info.

BorePlusPlus avatar Jan 21 '22 12:01 BorePlusPlus

Hi @BorePlusPlus, while this repo is shared as an example, we haven't fully tested two instances of analytics.js, and can't recommend it. I can foresee few issues here, including clash between cookie/localStorage data, and event handlers. We may look into supporting multiple writekeys in the future tho.

That aside, I think the issue you are seeing is related to the queue mechanism. So possibly both implementations are reading from the queue simultaneously. Haven't tested this, but might worth waiting for one instance to initialize before the next instance loads. Something like this:

window.analytics.ready(() => {
  AnalyticsBrowser.load({ writeKey: '...' })
    .then(() => {
      console.log('>>>>> next loaded');
    });
})

pooyaj avatar Jan 21 '22 21:01 pooyaj