DavidWells / analytics

Lightweight analytics abstraction layer for tracking page views, custom events, & identifying visitors
https://getanalytics.io
MIT License
2.43k stars 247 forks source link

How to pass custom property from instantiated plugin? #366

Closed coreybruyere closed 1 year ago

coreybruyere commented 1 year ago

Not sure if discussions are actively used in this repo, so asking here.

I'm using the analytics plugin with mixpanel. Is there a way to pass a custom property to mixpanel from the initialized plugin ? Example: Passing a property of site and value of blog in one place within plugin instantiation so that all events (page, track, identity) pass that custom property to mixpanel?

export const analytics = Analytics({
    app: 'website',
    debug: process.env.NODE_ENV !== 'production',
    plugins: IS_BROWSER ? [
        mixpanelPlugin({
            token: TOKEN,
            site: 'blog' //?/?
        }
    ] : []
});
DavidWells commented 1 year ago

You will want a custom plugin to alter the payload to the provider of your choice, in this case mixpanel.

Here is an example of a plugin that enriches track payload

export default function enrichMixpanel(pluginConfig = {}) {
  return {
    name: 'mixpanel-enrich',
    // Enrich payload for mixpanel plugin track
    'track:mixpanel': ({ payload }) => {
      console.log('payload', payload)
      return {
        ...payload,
        ...{
          properties: {
            ...payload.properties,
            ...{
              custom: 'thing',
            },
          },
        },
      }
    },
  }
}

Initialize and use a plugin like this before you load mixpanel plugin

coreybruyere commented 1 year ago

Thanks @DavidWells - Not sure I'm following the last part. Where should I initialize this plugin? In the plugins array?

DavidWells commented 1 year ago

yeah in the plugins array like this

import Analytics from 'analytics'
import enrichMixpanel from './my-mixpanel'
import mixepanel from '@analytics/mixepanel'

const analytics = Analytics({
  app: 'app-name',
  plugins: [
    enrichMixpanel({ opts }),
    mixepanel({
      trackingId: 'UA-121991123',
    })
  ]
})

export default analytics