Get a free website audit -

Free Audit

How to integrate Facebook pixel and Facebook pixel events with gatsbytjs website

Date: Wednesday August 26th, 2020


When building with react or gatsbyjs you have to build things slightly differently than normal.

Lets take the facebook pixel for example

When integrating the pixel if you follow the facebook pixel integration guidelines from facebook, they will tell you to copy a snippet of javascript code and place at the bottom of your head tag on your webpage

However... on gatsbyjs you can't amend the head tags directly, so we need a different approach!

We go to the plugin eco-system, luckily a kind developer has already created a gatsbyjs facebook plugin

https://www.gatsbyjs.com/plugins/gatsby-plugin-facebook-pixel/

Nice and straight forward, install the plugin with npm, then add the code to gatsby-config.js ensuring you add your pixel id. Simple instructions are on the link above

So what does this get you? Well this plugin will inject the facebook pixel javascript snippet on to your website, and this will track page views. This gives you a basis of the facebook pixel working

Adding facebook pixel events

Okay so the 1st step is done which is adding a facebook pixel, the next step is to track events. For this we need to take a quick look at the following documentation

https://developers.facebook.com/docs/facebook-pixel/implementation/conversion-tracking/

Facebook event tracking

This will shows us how to add an event

fbq('track', 'Purchase', {currency: "USD", value: 30.00});

Nice and simple, this is saying hey, when this event fires, track the event, the event is someone has purchased something and that purchase is worth $30.

You can the use this value to track ROI of facebook advertising

Okay but if you add that directly do gatsbyjs you'll get an error

fqb is not defined

So what now, well now we take a little trick from react

if (typeof window !== "undefined") {
  if (window.fbq != null) {
    window.fbq('track', 'Lead', {currency: "GBP", value: 1.00});                  }          
 }

This code is saying

  • Hey do we have a browser window type object
  • On that object can we find the facebook object
  • If we can lets use it and call the function to track

Okay but where do you put this?

Well I put this code on a form fire. We currently have a campaign running for a free website audit at getjuicy.co.uk/free-audit

On that page when the form is submitted, before form submission and it calls the email API I call the facebook function to track the event.

Now on the campaign I can track how many people responded to my advertising for a free audit.

As always if you need any help with this then let us know.

Back to News

info@getjuicy.co.uk

01425 476077

7B4 Kingsburys House
Fridays Cross Mews
Christchurch Road
Ringwood
BH24 1DG