Add Facebook Pixel Event Tracking in NextJS App Directory

dankedev

Hadie Danker

Posted on June 17, 2023

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
💖 💪 🙅 🚩
dankedev
Hadie Danker

Posted on June 17, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related