analytics icon indicating copy to clipboard operation
analytics copied to clipboard

Global Analytics.enabled flag

Open ian opened this issue 4 years ago • 2 comments

Wanted to throw out the suggestion for a global on/off switch. It would be nice to be able to globally cripple Analytics.

Use case would be for development vs production:

const analytics = Analytics({
  app: 'my-app-name',
  enabled: process.env.ANALYTICS_ENABLED,
  plugins: [
    ...
  ]
})

ian avatar Apr 24 '21 14:04 ian

Hey, @ian interesting idea. I will think about how this might work.

The way I've seen folks doing this is by conditional loading of the plugins array like so:

const IS_DEV_ENV = process.env.NODE_ENV === 'development'
const IS_PROD_ENV = process.env.NODE_ENV === 'production'

// dev only
const devOnlyPlugins = [
  {
    name: 'logger',
    page: ({ payload }) => {
      console.log('page', payload)
    },
    track: ({ payload }) => {
      console.log('track', payload)
    },
    identify: ({ payload }) => {
      console.log('identify', payload)
    }
  },
]

// prod only
const prodOnlyPlugins = [
  googleAnalyticsPlugin({
    trackingId: GOOGLE_ANALYTICS
  }),
]

// both prod & dev
const loadInAllEnvPlugins = [
  originalSrcPlugin(),
]

const plugins = [
  ...loadInAllEnvPlugins,
  ...(IS_DEV_ENV) ? devOnlyPlugins : [],
  ...(IS_PROD_ENV) ? prodOnlyPlugins : [],
]

// Initialize analytics
const analytics = Analytics({
  app: 'my-app-name',
  plugins: plugins
})

// Use it 
analytics.page()

DavidWells avatar Apr 25 '21 19:04 DavidWells

Added this to the docs https://getanalytics.io/conditional-loading/#by-environment

DavidWells avatar Apr 25 '21 19:04 DavidWells