Facebook Pixel with React by Mohd Amir

Mohd Amir - Sep 20 - - Dev Community

Table of Contents

  1. About Me
  2. Creating Facebook Pixel
  3. Domain Verification for Facebook Pixel
  4. Implementing Facebook Pixel in Vite React App
  5. Ensuring Security While Loading Facebook Pixel
  6. Code Structure
  7. How to Use

About Me

Hi, I’m Mohd Amir, a full-stack developer with expertise in scalable and maintainable apps. I enjoy diving into cutting-edge tech. You can check out my work on GitHub or follow me on Twitter.


Creating Facebook Pixel

To get started with Facebook Pixel:

  1. Log in to your Facebook Events Manager.
  2. Go to the Pixels tab under Data Sources.
  3. Click Create a Pixel and give it a name.
  4. You'll be provided with a Pixel ID and a base code to implement on your website.

Domain Verification for Facebook Pixel

To verify your domain on Facebook:

  1. Go to Facebook Business Settings > Brand Safety > Domains.
  2. Add your domain, and Facebook will give you one of three methods:
    • Meta-tag: Add the meta tag to your website’s <head>.
    • HTML file upload: Upload an HTML verification file to your root directory.
    • DNS TXT Record: Add a DNS record to your domain’s DNS configuration.
  3. Verify once the appropriate method is implemented.

Implementing Facebook Pixel in Vite React App

Now, let’s integrate Facebook Pixel into your Vite React app:

1. Set up Environment Variable

Create a .env file in the root of your Vite project and add your Facebook Pixel ID:

VITE_FB_PIXEL_ID=your_facebook_pixel_id
Enter fullscreen mode Exit fullscreen mode

2. Create a Custom Hook to Load Facebook Pixel

Create a facebookPixelHook.js inside the hooks/ directory:

import { useEffect } from "react";

const useFacebookPixel = (pixelId) => {
  useEffect(() => {
    // Load the Pixel script only if it's not already loaded
    if (!window.fbq) {
      (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"
      );

      // Initialize Facebook Pixel
      window.fbq("init", pixelId);
    }

    // Track page view
    window.fbq("track", "PageView");
  }, [pixelId]);
};

export default useFacebookPixel;
Enter fullscreen mode Exit fullscreen mode

3. Use the Hook in Your React Component

Use this hook in your component to initialize and track events:

import React from "react";
import useFacebookPixel from "./hooks/facebookPixelHook";

const MyApp = () => {
  const pixelId = import.meta.env.VITE_FB_PIXEL_ID;

  useFacebookPixel(pixelId);

  return <div>Your app is being tracked by Facebook Pixel.</div>;
};

export default MyApp;
Enter fullscreen mode Exit fullscreen mode

Ensuring Security While Loading Facebook Pixel

Although the Pixel ID is safe to expose, it’s good practice to:

  1. Store Pixel ID in environment variables (as shown above).
  2. Load the Pixel script dynamically from the backend if desired, which avoids direct exposure of the Pixel ID in the front-end code.
  3. Consider Facebook Conversions API for server-side event tracking if you're looking for an even more secure method.

Code Structure

Here is the general structure of the codebase:

  • src/
    • main.jsx: Entry point for the React application.
    • App.jsx: Main component of the application.
    • hooks/
    • facebookPixelHook.js: Custom hook to load Facebook Pixel.
    • utils/
    • facebookEvents.js: (Optional) You can add utility functions for custom events.
    • config.js: (Optional) Store the Pixel ID configuration.
  • index.html: Entry point for the HTML.
  • vite.config.js: Vite configuration.
  • .env: Environment variables (like VITE_FB_PIXEL_ID).

How to Use

Here’s how to use the project:

  1. Clone the repository:
   git clone https://github.com/webdev-mohdamir/facebook-pixel-with-react.git
Enter fullscreen mode Exit fullscreen mode
  1. Install the dependencies:
   npm install
Enter fullscreen mode Exit fullscreen mode
  1. Start the development server:
   npm run dev
Enter fullscreen mode Exit fullscreen mode
  1. Open the application in your browser at http://localhost:3000.

  2. Submit the form to track custom events (if you added custom events).


Final Thoughts

That’s it! Now you have a fully functioning Facebook Pixel implementation in your React app. Don’t forget to verify your domain and use Meta Pixel Helper for debugging your Pixel events.

Also, remember: Coffee is the key to debugging success ☕!

. . . . . . . . . . . . . . . . .
Terabox Video Player