Search code examples
reactjsfacebookenvironment-variables

set up Facebook Pixel only for production in ReactJS


I am using React as my front-end (and Rails as my back-end).

I am setting up the Facebook Pixel Events Manager to track my Facebook ads on my website.

So I added this script to my public/index.html:

<!-- Facebook Pixel Code -->
<script>
  !function(f,b,e,v,n,t,s)
  {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
  n.callMethod.apply(n,arguments):n.queue.push(arguments)};
  if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
  n.queue=[];t=b.createElement(e);t.async=!0;
  t.src=v;s=b.getElementsByTagName(e)[0];
  s.parentNode.insertBefore(t,s)}(window, document,'script',
  'https://connect.facebook.net/en_US/fbevents.js');
  fbq('init', 'MYID');
  fbq('track', 'PageView');
</script>
<noscript><img height="1" width="1" style="display:none"
  src="https://www.facebook.com/tr?id=MYID&ev=PageView&noscript=1"
/></noscript>
<!-- End Facebook Pixel Code -->

and in my React Components I added this callback function anytime a button is clicked and raise an event:

() => fbq('track', 'MyEvent');

It seems to work, although I need my pixels to fire only in production. I can't access process.env.NODE_ENV in public/index.html.

What can I do to have this code used only in production ?


Solution

  • thanks to @Dvid Silva and @Russ Brown, I finaly went with the following solution: create two separate index.html files: dev-index.html and prod-index.html

    in my config/path.js:

    module.exports = {
    #[...]
      appHtml: process.env.NODE_ENV === 'production' ? resolveApp('public/prod-index.html') : resolveApp('public/dev-index.html'),
    #[...]
    };
    

    Both index files are identical except the production one has the Facebook Pixel inside its <head> tag.