DEV Community

Hadie Danker
Hadie Danker

Posted on

Add Facebook Pixel Event Tracking in NextJS App Directory

Facebook Pixel is a powerful tool that allows you to track and optimize conversions from Facebook ads, build custom audiences, and measure the effectiveness of your marketing campaigns.

And this how to itegrate facebook pixel with easy with react-facebook-pixel

Create component in directory component (for example)
src/components/pixel-events.tsx

"use client";
import React, { useEffect } from "react";
import { usePathname, useSearchParams } from "next/navigation";

export const FacebookPixelEvents: React.FC = () => {
  const pathname = usePathname();
  const searchParams = useSearchParams();

  useEffect(() => {
    import("react-facebook-pixel")
      .then((x) => x.default)
      .then((ReactPixel) => {
        ReactPixel.init("FACEBOOK_PIXEL_ID"); //don't forget to change this
        ReactPixel.pageView();
      });
  }, [pathname, searchParams]);

  return null;
};

Enter fullscreen mode Exit fullscreen mode

And then can be imported into a layout.

import { Suspense } from 'react'
import { FacebookPixelEvents } from '../components/pixel-events'

export default function Layout({ children }) {
  return (
    <html lang="en">
      <body>
        {children}

        <Suspense fallback={null}>
          <FacebookPixelEvents />
        </Suspense>
      </body>
    </html>
  )
}
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
musamaashraf profile image
Usama Ashraf

How can we track custom events in this?

Collapse
 
hajilex profile image
Hajilex

I discovered a solution:

Create a function in the same file as the code above, then import and run it where you want.

export const nameEvent = async () => {
const { default: ReactPixel } = await import("react-facebook-pixel");
ReactPixel.init("Your Pixel ID");
ReactPixel.track("Name", { data });
};