mixpanel / mixpanel-node

A node.js API for mixpanel
http://www.mixpanel.com
MIT License
477 stars 159 forks source link

Events not firing #175

Closed hansy closed 4 years ago

hansy commented 4 years ago

I'm not sure why, but no events are being sent via the track function.

import Mixpanel from 'mixpanel'

const mixpanel = Mixpanel.init(process.env.MIXPANEL_TOKEN)
mixpanel.track('testEvent', { distinct_id: "abc123" })

I don't even know how to debug this. I even tried adding a callback argument to look for an error, but nothing:

mixpanel.track('testEvent', { distinct_id: "abc123" }, (err) => {
  console.log(err) // no output
  console.log('Something') // no output
})

What am I doing wrong?

System info: Mixpanel v0.13.0 Node v14.5.0 MacOS Catalina 10.15.6

hansy commented 4 years ago

Since I was using this in an async serverless function I needed to wait for the Mixpanel request to complete. I ended up turning track into a Promise via promisify to await the Mixpanel response.

abierbaum commented 1 year ago

@hansy Thanks for this tip. Saved me a ton of time. I really miss having promises in this API.

steviec commented 1 year ago

It's kinda ridiculous. The library just doesn't work in AWS lambda at all unless you wrap it since the callback doesn't have time to fire before the lambda ends.

walterholohan commented 1 year ago

If anyone wants an example of how to create a promise wrapper here is one.

/**
 * Due to the fact that the mixpanel library does not support promises
 * we have to wrap the track function in a promise. Otherwise the
 * lambda function will finish before the request has been sent.
 * @param event - The event to track
 * @param properties - The properties to track with the event
 * @param mixpanel - The mixpanel instance
 * @param userId - The user id
 * @returns A promise that resolves when the track request has been sent
 */
async function mixpanelAsyncTrack({
  event,
  properties,
  mixpanel,
  userId,
}: {
  event: string
  userId: string
  properties?: { [key: string]: string | number | boolean | undefined }
  mixpanel: Mixpanel.Mixpanel
}) {
  return new Promise((resolve, reject) => {
    mixpanel.track(event, { distinct_id: userId, properties }, (err) => {
      if (err) {
        reject(err)
      } else {
        resolve('success')
      }
    })
  })
}
Collin0810 commented 1 year ago

@walterholohan Thanks! Have been struggling for hours to set up Mixpanel event tracking in a NextJS API route (which gets turned into a serverless lambda function when deploying to Vercel into production). This works great!