analytics icon indicating copy to clipboard operation
analytics copied to clipboard

Re-init dynamically / switch token

Open tquiroga opened this issue 5 years ago • 7 comments

I'm trying to initialise my Mixpanel after my user login. So I would need to use a specific token according to the type of user (2-sided app).

What the best way to re-initialise Analytics?

tquiroga avatar Dec 18 '20 11:12 tquiroga

Hello there! Good question

I just pushed a release in [email protected] that makes it easy with the enabled flag.

googleAnalytics({
   trackingId: 'ua-111-22222',
+  enabled: false,
})

This will work for all plugins including mixin panel

See more in the docs here: https://getanalytics.io/conditional-loading/

import Analytics from 'analytics'
import googleAnalytics from '@analytics/google-analytics'

/* initialize analytics and load plugins */
const analytics = Analytics({
  app: 'awesome-app',
  plugins: [
    // Google analytics will only load if 
    // analytics.plugins.enable('google-analytics') is called
    googleAnalytics({
      trackingId: 'ua-111-22222',
      enabled: false,
    }),
    {
      name: 'plugin-1',
      enabled: true, // <= default
      initialize: () => {
        // setup logic, load scripts etc
      },
      page: ({ payload }) => console.log('plugin-x page view', payload),
      // ... other methods
    },
    {
      name: 'plugin-2',
      enabled: false, // <= plugin is disabled. 
      initialize: () => {
        // This will fire when analytics.plugins.enable('plugin-2') is called
        console.log('initialization logic will only run once I am loaded')
      },
      page: ({ payload }) => {
        console.log('plugin-2 page view', payload)
      },
    },
    {
      name: 'plugin-3',
      page: ({ payload }) => {
        console.log('plugin-3 page view', payload)
      },
    },
  ]
})

/* Later in your app code... */

// Send page view to all enabled plugins
analytics.page()

// Enable google analytics based on user input...
analytics.plugins.enable('google-analytics').then(() => {
  // Send page view to all enabled plugins including Google analytics
  analytics.page()
})

// You can also disable plugins dynamically
analytics.plugins.disable(['plugin-1', 'plugin-3']).then(() => {
  // Send tracking event to all enabled plugins 
  analytics.track('buttonClicked', { price: 100 })
})

DavidWells avatar Dec 23 '20 05:12 DavidWells

@DavidWells hey, is there also any build-in way to store all events which was fired while plugin was disabled and send them right after we enabled it?

For example for usage with OneTrust, when we don't have user consent for trackers we just accumulate them till we receive consent

layonez avatar Aug 02 '21 11:08 layonez

Hello @layonez

I like this idea. I don't think its automagically baked in but you can do this via .on listeners or with a custom plugin.

Right now you can save events and replay this via middleware.

Similar to https://github.com/DavidWells/analytics/issues/186#issuecomment-882169264

You can listen to the trackStart, track, or trackEnd event in a plugin

Here is an example plugin. Check the instance.getState() call to check if a plugin is disabled or not

export default function pluginExample(userConfig) {
  // return object for analytics to use
  return {
    /* All plugins require a name */
    name: 'deferrer-plugin',
    page: ({ payload, instance }) => {
      const plugins = instance.getState('plugins')
      if (plugins.xyz.disabled) {
            // save events for replay later
      }
    },
    track: ({ payload }) => {
      const plugins = instance.getState('plugins')
      if (plugins.xyz.disabled) {
            // save events for replay later
      }
    },
  }
}

DavidWells avatar Aug 14 '21 21:08 DavidWells

@DavidWells comment goes over half of what we need, loading plugins as disabled helps, but we need to swap out their tokens because we don't have those at compile time only runtime (and it's currently easier to hot-load the plugin early in app startup vs. restructure all of our analytics code to be lazy-loaded)

Is there a way to uniformly edit configuration as part of plugin hooks before you initialize them again that isn't currently documented?

StrangeWill avatar Sep 27 '22 04:09 StrangeWill

@StrangeWill did you ever find a solution to this? I have almost the identical need. I'm guessing you are trying to build something you can share around, pass the config in at runtime, and have it all still be the same Analytics object.

arb avatar May 30 '23 13:05 arb

Similar but even more simple: Our goal is to not compile stuff into our JS app (because that's inflexible), but to pull configuration from the back-end at runtime.

We haven't spent a lot of time on it, but will probably have something working within the next 30 days since this problem is annoying and needs to be fixed on our end -- once we find it we'll share it!

StrangeWill avatar May 30 '23 18:05 StrangeWill

@arb Have you been able to find solution for this? I am facing the exact scenario you described. I am asynchronously getting tokens for analytics so I cannot simply initiate it upfront.

tomsq avatar Mar 15 '24 12:03 tomsq