analytics-react icon indicating copy to clipboard operation
analytics-react copied to clipboard

Enable/Disable Analytics in development ?

Open LoiKos opened this issue 5 years ago • 2 comments

I'm working on my team workflow for analytics and i'm looking for a way to Enable/Disable analytics in development environment.

//package.json
    "start": "react-scripts start",
    "start:analytics": "REACT_APP_SEGMENT="Dev key" react-scripts start",

This seems to work but i don't really understand how analytics script work behind the hood but it seems to save all analytics events done even if the script doesn't load .

Is this acceptable or could you show me how to prevent sending data in this case ?

LoiKos avatar Jan 27 '20 15:01 LoiKos

Easiest way I found to do this was to conditionally load analytics if NODE_ENV==='production' on mount. So in a class component, that would look like:

componentDidMount() {
  if (process.env.NODE_ENV === 'production') {
    // load segment
    Segment.load('SEGMENT_KEY')
    Segment.page()
  }
}

I also separated out the segment load script and remove the analytics.load call at the end of the file. That way I can import it manually and have a cleaner way to call it throughout my app rather than using window.analytics everywhere. Code here:

// segment snippet
!function() {
  var analytics = window.analytics = window.analytics || [];
  if (!analytics.initialize)
    if (analytics.invoked) window.console && console.error && console.error("Segment snippet included twice.");
    else {
      analytics.invoked = !0;
      analytics.methods = ["trackSubmit", "trackClick", "trackLink", "trackForm", "pageview", "identify", "reset", "group", "track", "ready", "alias", "debug", "page", "once", "off", "on"];
      analytics.factory = function(t) {
        return function() {
          var e = Array.prototype.slice.call(arguments);
          e.unshift(t);
          analytics.push(e);
          return analytics
        }
      };
      for (var t = 0; t < analytics.methods.length; t++) {
        var e = analytics.methods[t];
        analytics[e] = analytics.factory(e)
      }
      analytics.load = function(t, e) {
        var n = document.createElement("script");
        n.type = "text/javascript";
        n.async = !0;
        n.src = "https://cdn.segment.com/analytics.js/v1/" + t + "/analytics.min.js";
        var a = document.getElementsByTagName("script")[0];
        a.parentNode.insertBefore(n, a);
        analytics._loadOptions = e
      };
      analytics.SNIPPET_VERSION = "4.1.0";
      // remove this line and call it in componentDidMount instead
      // analytics.load('SEGMENT_KEY')
    }
  return analytics
}();

export default window.analytics;

joelrojo avatar Apr 11 '20 23:04 joelrojo

await firebase.analytics().setAnalyticsCollectionEnabled(true);

Abdelaty-magdy avatar Jun 19 '23 11:06 Abdelaty-magdy