mixpanel / mixpanel-js

Official Mixpanel JavaScript Client Library
https://mixpanel.com/help/reference/javascript
Other
888 stars 312 forks source link

Pass custom `device_id` to library initialization #422

Open andirsun opened 8 months ago

andirsun commented 8 months ago

Context about why we need this change:

doc-han commented 7 months ago

device_id is unique to the user's device and not the user's account in your DB. I don't understand how you're generating device_id server-side(Next.js middleware).

andirsun commented 7 months ago

@doc-han hey thanks for the answer! Basically I am generating a custom uuid in the middleware to act as a device id for statsig.

doc-han commented 7 months ago

device_id in mixpanel isn't something you're supposed to be worried about changing. It's an anonymous id which isn't tied to anything so let mixpanel handle that.

A uuid generated by you is supposed to used alongside the identify function. Hence, when you generate the uuid in the middleware. share it with the front-end and after mixpanel init in the front-end just identify with the uuid.

Identify literarily tells mixpanel that the device_id and the uuid is the same person. Hence any actions tracked under device_id will be associated with the uuid.

andirsun commented 7 months ago

Also would be great that I coud pass device_id for my mixpanel implementation on figma plugin. https://github.com/mixpanel/mixpanel-js/issues/388

Fy- commented 6 months ago

Same here. In my setup, device_id is a cookie set by my Go webserver for all web clients, including guests, and it is distinct from my user UUID (and used for mixpanel server events, eg. ssr, api events, webhooks, etc...). It would be beneficial to allow passing a custom function so that the same device ID can be used consistently on both client and server sides (e.g., get_device_id: () => getCookie('__did')).

This is ugly but it works (after initial load or if you do the page event manually):

// with cookie_name: '__mp_data' in mixpanel.init opts.

const mpData = cookies.mp___mp_data
if (mpData) {
  const mpDataJson = JSON.parse(decodeURIComponent(mpData))
  mpDataJson.$device_id = cookies.__did
  mixpanel.register({
    $device_id: cookies.__did,
  })
  mpCookie.set('mp___mp_data', JSON.stringify(mpDataJson), {
    expires: new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365),
    domain: '.domain.com',
  })
}

Note: The __did cookie is used solely for device identification (not user identification) by my webserver and is also passed along for server-side events. For instance, a user may have multiple devices, each with different __did values, but the UUID will always remain the same for an identified user.