mixpanel / mixpanel-js

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

Avoid initializing mixpanel when NODE_ENV is 'development' #300

Closed kylemh closed 3 years ago

kylemh commented 3 years ago

If the title of this issue cannot be the default behavior, I'm wondering how else I can avoid spending money on Mixpanel while doing dev work, but still maintain the Mixpanel instance so I don't have run-time errors.

Doing

  await Mixpanel.init(token);
  if (process.env.NODE_ENV === 'development') Mixpanel.disable();

doesn't prevent requests from going out.

tdumitrescu commented 3 years ago

Are you sure you're using the browser JS SDK (this repo)? It doesn't look like it from your example - mixpanel.init() is not an async function, and process.env won't typically be present in a browser environment. And mixpanel.disable() is certainly supposed to keep .track() calls from going out over the network, we haven't had other reports of problems with it.

To answer the general question about environment management, there are a number of approaches possible. One is to inject a different token in different environments, so they go to different projects. A request with an invalid token will just get dropped at the API layer, or you could set up a real dev project on our free plan, which gives more than enough data for any dev work. Alternatively some people use thin wrappers around MP which can provide disabled behavior in test environments while working well with test spies.

kylemh commented 3 years ago

import Mixpanel from 'mixpanel-browser';

It appears so. I'm just looking at this code somebody else wrote. I'll remove await. I'm aware that process.env won't be aware on the run-time, but my understanding was that when using Webpack, process.env.NODE_ENV is compiled out on build?

I tried doing the fake token trick, but the Mixpanel global didnt exist and led to run-time errors, but maybe it's because of process.env not working as you suggested.

I changed my code to:

Mixpanel.init(token);
if (typeof window !== 'undefined' && window.location.hostname === 'localhost') Mixpanel.disable();

and we're good to go.