How To Set up a Facebook Pixel to Track Prospect Behavior in NodeJS / ExpressJS

Learn how to track events on your website, customize tracking and optimize Facebook Ads

Bahadir Balban

Buzz Founder

@buzzdevelopers47713

Everybody hates Facebook and all the tracking they do with their users. I don’t disagree that being tracked isn’t nice. There is something I find to be true though, and that is, Facebook is a utility that lets you reach the right kind of users, with the right messaging. Imagine that you have a useful service/product for a particular audience. How is that audience going to find out about you? Whatif that audience badly needs what you are providing, but you don’t have the means to reach them? Facebook is a utility that helps everyone in this case, where it makes it efficient for two parties to meet for a trade.

Facebook has a tool called the Facebook Pixel, that makes it easy to: (a) Reach people again and again who visited your website (b) Track user behavior on your website so that your business that’s already trying hard to be efficient can evaluate how their spending for reach out is performing with regard to conversions: sign ups, purchases, checkout initiations and so on.

Use the Facebook Pixel to reach and analyze your visitors (Photo Credit: maxpixel.net)

Clearly using a Facebook Pixel is useful, but the last time I ever thought about using it, or any time I tried to do anything with it failed. Well, it is because I found it to be such a hassle. You need to know html, javascript, if you want to get information about anything other than “pageviews”. How are you going to enable each action on each button on your site? Even if you know it, you would probably be lazy to discover how to do it properly.

Well, with the motivation that I can do this not just for myself but for others on a product that I am building, I found out how to do it and in this post I will cover it.

Step 1: Create your Facebook Pixel

Go to this link: https://www.facebook.com/events_manager, and select “Add New Data Source > Facebook Pixel” on the left.

Then follow the guide and click “Email instructions to myself” or a variation of it as below:

Step 2: Add the Facebook Pixel Script to your website:

You will see the code you need to add to your <HEAD> html tag that looks like this as of this writing:


<!-- 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', 'YOUR-PIXEL-IDENTIFICATION-NUMBER-GOES-HERE');
  fbq('track', 'PageView');
</script>
<noscript><img height="1" width="1" style="display:none"
  src="https://www.facebook.com/tr?id=YOUR-PIXEL-IDENTIFICATION-NUMBER-GOES-HERE&ev=PageView&noscript=1"
/></noscript>
<!-- End Facebook Pixel Code -->

Here is how it looks if you convert this to a Pug/Jade snippet (my favorite html templating engine):

if fbtracker && fbtracker.tracking == "on" && fbtracker.trackid
      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', #{fbtracker.trackid});
        fbq('track', 'PageView');

Now I am very cautious about 3rd party scripts that have questionable page load times + where I don’t have detailed knowledge of what the script is doing.

This script is required to be included in almost all of your pages. Therefore, what I needed was the ability to include this script conditionally, only when I enable it to run. Hence you see the first line:

if fbtracker && fbtracker.tracking == "on" && fbtracker.trackid

This is a simple object that I populate and pass on every page before rendering. If the variable is available and has tracking in on state, and there is a tracking ID, the script is included, otherwise excluded.

The problem with making a database-populated object globally available on all of your render calls in ExpressJS is that you need to define a middleware, then assign the result of that middleware to a req object, then, pass the object to every render() call. There is a way to avoid this, and here is the approach I used for it.

Step 3: (ExpressJS only) How to populate and pass a global object to all your render() calls without cluttering your application

In your app.js file you add the following calls:

app.use(function(req, res, next) {
  return models.Fbtracker.findOne({where: {name: "main"}}).then(tracker => {
      req.fbtracker = tracker;
      next();
  })
});
// middleware for whether we use fb tracker or not.
app.use(function(req, res, next) {
  res.locals.fbtracker = req.fbtracker;
  next();
});

In this code:

We create a promise to query the database for the tracker object

We assign the object to req.tracker, then call next();

In addition, we call another middleware that assigns the req.fbtracker to res.locals.fbtracker.

When you do this, the fbtracker object will be available in all of your pug files, and without having to pass it as an explicit parameter.

Step 4: Integration of Facebook Tracking Events

Going back to Facebook, they made a list of standard events at this link that you can use in your application. The summary is that you need to add an event call to all your button click handlers for each event.

Lead, InitiateCheckout, Subscribe, Purchase events

In my scenario, I was interested in events such as a user submitting their email address as a lead, (“Lead”) event. User making a purchase decision and pressing the buy button on a product or a subscription plan, represented by the (“InitiateCheckout”) event, and also, the event where they go through payment, such as the (“Purchase”) event for a one-off product, and (“Subscribe”) event for when they subscribe to a periodic payment plan.

Here is a sample tracking code for these events:

fbq('track', 'InitiateCheckout', {
    name: name,
    value: price,
    currency: "USD"
});

In order to trigger these events, you need to associate the correct reporting call when the event occurs, such as a button click.

Luckily for each of these cases I had a <button> element already defined. I believe every website has buttons for these events, and all you need is the button element, and associate the tracking call with its event handler.

JQuery to the rescue

This can be done in plain javascript, but I preferred to use JQuery as I find it to be simpler.

Define a CSS class to identify the group of buttons associated with the same event, e.g. “track-purchase”:

button.btn.btn-primary.mt-3(type="submit" id="payment-button") Submit Payment

becomes

button.btn.btn-primary.mt-3.track-purchase(type="submit" id="payment-button") Submit Payment

We use a CSS class instead of an “id”, since you can have multiple buttons with the same event on the same page.

You can than grab all the buttons of this kind in Jquery as follows:

$(".track-purchase").on('click',
        function() {
            fbq('track', 'Purchase', { })
        }
);

You can test the call is indeed firing by adding a console.log(“Hello Purchase!”) call inside the function definition, pressing the button and observing the javascript console in the Chrome browser.

Passing event related information

You need to handle one more step - you need to pass more information about each event. E.g. if it is a product being purchased, pass the price, currency, name of the product or more data. I was able to do this as follows:

In your pug file where you populate the product, you can define a “data” attribute for the very button you added this tracking handler. For example:

button.btn.btn-primary.mt-3.track-purchase(type="submit" id="payment-button", 
data-track-name=product.name, 
data-track-price=product.price) Submit Payment

Here we define 2 attributes, data-track-name, data-track-price. This is easy to populate as the product object is already available for rendering the page.

The other option is to scrape the page html elements using Jquery by knowing where you included the price and other information. This is a fragile method as when the html changes your code will likely break. By using a data attribute within the button, we isolate everything we need about this work inside the button element.

Then, here is how your latest jquery code looks like for this button and event:

$(".track-purchase").on('click',
        function() {
            let name = $(this).attr("data-track-name");
            let price = $(this).attr("data-track-price");
            fbq('track', 'Purchase', {
                name: name,
                value: price,
                currency: "USD"
            })
        }
);

See how the attributes are obtained within the function call, and passed to the facebook tracking call.

Step 5: Check out the results in your Facebook Event Manager/Ads Dashboard

You should now see the events being fired in your facebook event dashboard.

The Full JQuery Source Code:

//
// All button handlers on all pages re: facebook tracking are populated in this one file.
//
$(document).ready (function(){
    // Item analytics attributes like price are embedded in the item html
    $(".track-init_checkout_product").on('click',
        function() {
            let name = $(this).attr("data-track-name");
            let price = $(this).attr("data-track-price");
            fbq('track', 'InitiateCheckout', {
                name: name,
                value: price,
                currency: "USD"
            });
        }
    );
    $(".track-purchase").on('click',
        function() {
            let name = $(this).attr("data-track-name");
            let price = $(this).attr("data-track-price");
            fbq('track', 'Purchase', {
                name: name,
                value: price,
                currency: "USD"
            })
        }
    );
    $(".track-init_checkout_plan").on('click',
        function() {
            let name = $(this).attr("data-track-name");
            let price = $(this).attr("data-track-price");
            let period = $(this).attr("data-track-period");
            fbq('track', 'InitiateCheckout', {
                name: name,
                value: price,
                period: period,
                currency: "USD",
            });
        }
    );
    $(".track-subscribe").on('click',
        function() {
            let name = $(this).attr("data-track-name");
            let price = $(this).attr("data-track-price");
            let period = $(this).attr("data-track-period");
            fbq('track', 'Subscribe', {
                name: name,
                value: price,
                period: period,
                currency: "USD",
            });
        }
    );
    $(".track-lead").on('click',
        function() {
            fbq('track', 'Lead', {})
        }
    );
});

Conclusion and Remarks

It surely takes a while to implement this all on a new website from scratch. If you are starting a web-based business and looking for a solution that lets you do all of this, you can try SaaSBox. SaaSBox gives online entrepreneurs a fast way to launch an MVP.

More information

More information about the Facebook Pixel can be found here.

An awesome post on how to optimize Facebook Ads from an Ads expert.




Join The Discussion