Skip to content

Integration Request: Facebook Pixel #54

Closed

Description

@jasongi-actu

Currently in the process of integrating analytics, I really like the concept and the library!

Am probably going to end up writing a barebones Facebook Pixel plugin, just thought I would make a ticket to see it. It has a pretty simple API that I think will map well.

Some issues I've encountered:

  • Facebook PageView event doesn't let you tell it what page you're viewing, it takes it straight from the URL. It also does this automatically (even in SPAs) unless you configure disablePushStateTracking
  • It doesn't look like analytics standardises what you pass to identify which makes it hard to make a single identify call if you are for instance using segment and facebook which have different field names.

Activity

  1. DavidWells commented on May 21, 2020

    @DavidWells
    Owner

    Hey @jasongi-actu

    A fb pixel would be a great plugin 😃

    Facebook PageView event doesn't let you tell it what page you're viewing, it takes it straight from the URL. It also does this automatically (even in SPAs) unless you configure disablePushStateTracking

    When analytics.page() is called it uses a similar mechanism where it will grab the current page url & title.

    It doesn't look like analytics standardises what you pass to identify which makes it hard to make a single identify call if you are for instance using segment and facebook which have different field names.

    The data passed into the identify call is up to the application itself. The only required field is the userId

    Inside of the plugin, you can manipulate/enrich the data however you'd like. Here's a plugin scaffold:

    export default function facebookPixelPlugin(userConfig = {}) {
      return {
        name: 'facebook-ads',
        config: {
          ...defaultConfig,
          ...userConfig
        },
        initialize: ({ config }) => {
          // Load pixel script here
        },
        page: ({ payload }) => {
          // trigger page pixel
        },
        /* Track event */
        track: ({ payload }) => {
           // trigger custom event pixel ? idk if thats a thing 😃
        },
        /* Identify user */
        identify: ({ payload }) => {
          // Alter the payload & payload.properties however you want before 
          // triggering the pixel 
        },
        loaded: () => {
          return !!window.providerExampleLoaded
        }
      }
    }

    It is possible to send specific calls to specific providers like so:

    // Disable sending user data to specific analytic tools
    analytics.identify('xyz-123', { other: 'info' }, {
      plugins: {
        // disable sending this identify except to facebook
        all: false,
        'facebook-ads': true
      }
    })
    

    More in the docs on this here https://getanalytics.io/tutorials/sending-provider-specific-events/

  2. stefl commented on Nov 29, 2020

    @stefl

    I've put together a sketch for this that works with my Next JS app.

    let fb;
    let fbLoaded = false;
    export default function facebookPixelPlugin(userConfig = {}) {
      return {
        name: "facebook-ads",
        config: {
          ...userConfig,
        },
        initialize: async ({ config }) => {
          const { pixelId } = config;
          await import("react-facebook-pixel")
            .then((module) => (fb = module.default))
            .then(() => {
              if(!fbLoaded) {
                fb.init(pixelId, {
                  autoConfig: true,
                  debug: true,
                });
                fbLoaded = true;
              }
            });
        },
        page: ({ payload }) => {
          fb.pageView();
        },
        /* Track event */
        track: ({ payload }) => {
          console.log("facebook track", payload)
          fb.track(payload.event, payload.properties)
        },
        /* Identify user */
        identify: ({ payload }) => {
          // I believe FB doesn't have an identify API any more
        },
        loaded: () => {
          return fbLoaded;
        },
      };
    }
  3. jjoyce0510 commented on Apr 21, 2021

    @jjoyce0510

    Hi folks. Looks like this thread has been inactive for some time... Are there plans to productionize this?

  4. DavidWells commented on May 5, 2021

    @DavidWells
    Owner

    Happy to accept a PR on this 😃

  5. DavidWells commented on Jul 20, 2021

    @DavidWells
    Owner

    Moved to #153

  6. pelim commented on May 27, 2025

    @pelim
    let fbqReady = false;
    
    export default function facebookPixelPlugin(userConfig = {}) {
      const config = {
        options: { autoConfig: true, debug: true },
        ...userConfig
      };
    
      return {
        name: 'facebook-ads',
        config,
    
        /**
         * Injects Facebook Pixel script and initializes the pixel
         */
        initialize: ({ config }) => {
          const { pixelId, options } = config;
          if (!pixelId || fbqReady) return;
    
          /* Load standard Facebook Pixel 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 = true;
            n.version = '2.0';
            n.queue = [];
            t = b.createElement(e);
            t.async = true;
            t.src = v;
            s = b.getElementsByTagName(e)[0];
            s.parentNode.insertBefore(t, s);
          })(window, document, 'script', 'https://connect.facebook.net/en_US/fbevents.js');
    
          /* Initialize Pixel */
          window.fbq('init', pixelId, options);
          fbqReady = true;
        },
    
        /**
         * Track a page view
         */
        page: () => {
          if (!fbqReady) return;
          window.fbq('track', 'PageView');
        },
    
        /**
         * Track a custom event
         */
        track: ({ payload }) => {
          if (!fbqReady) return;
          const { event, properties } = payload;
          window.fbq('track', event, properties);
        },
    
        /**
         * Identify a user (no-op, FB Pixel doesn't support identify)
         */
        identify: () => {},
    
        /**
         * Return whether the pixel script has loaded
         */
        loaded: () => fbqReady
      };
    }
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions