26

I know this may be a dumb question. How can I do to use facebook pixel on a next.js react app ?

5 Answers5

46

there are no dumb questions.

You can see nextjs example about how implements fb pixel. Nextjs Facebook Pixel

Alan
  • 9,167
  • 4
  • 52
  • 70
Nico
  • 743
  • 5
  • 8
22

Solution with typescript and hook with NextJs

  1. Install react-facebook-pixel yarn add react-facebook-pixel
  2. In your file _app.tsx
// pages/_app.tsx

import { useEffect } from 'react'
import { useRouter } from 'next/router'

const App = ({ Component, pageProps }) => {
  const router = useRouter()

  useEffect(() => {
    import('react-facebook-pixel')
      .then((x) => x.default)
      .then((ReactPixel) => {
        ReactPixel.init('XXXXXXXXXXXXXXXXXXXXX') // facebookPixelId
        ReactPixel.pageView()

        router.events.on('routeChangeComplete', () => {
          ReactPixel.pageView()
        })
      })
  }, [router.events])

  

  return <Component {...pageProps} />
}

export default App

Remark: it works with typescript or JavaScript

Alan
  • 9,167
  • 4
  • 52
  • 70
13

Use the new Script component released in Next.js version 11. Import the below into your _app.js.

import { useEffect } from 'react'
import { useRouter } from 'next/router'
import {pageview, FB_PIXEL_ID} from '../../lib/fpixel'
import Script from 'next/script'

const handleRouteChange = () => {
  pageview()
}

const FB_PIXEL_ID = process.env.NEXT_PUBLIC_FACEBOOK_PIXEL_ID

const pageview = () => {
  window.fbq('track', 'PageView')
}

const FacebookPixel = ({ children }) => {
  const router = useRouter()

  useEffect(() => {
    // the below will only fire on route changes (not initial load - that is handled in the script below)
    router.events.on('routeChangeComplete', handleRouteChange)
    return () => {
      router.events.off('routeChangeComplete', handleRouteChange)
    }
  }, [router.events])

  return (
    <Script id="facebook-pixel">
      {`
        !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', ${FB_PIXEL_ID});
        fbq('track', 'PageView');
      `}
    </Script>
  )
}

export default FacebookPixel

UPDATE

Do not use strategy="lazyOnload". I was previously using this and the script was more likely to be blocked by adblocker if using this method.

Jeremy Lynch
  • 6,780
  • 3
  • 52
  • 63
5

There's a library for React called react-facebook-pixel. In order to make it work with NextJs, try this solution in your _app.jsx file:

function FacebookPixel() {
  React.useEffect(() => {
    import("react-facebook-pixel")
      .then((x) => x.default)
      .then((ReactPixel) => {
        ReactPixel.init('pixel ID here');
        ReactPixel.pageView();

        Router.events.on("routeChangeComplete", () => {
          ReactPixel.pageView();
        });
      });
  });
  return null;
}


export default function App({ Component, pageProps }) {
  return (
    <>
      <Head>
        <meta charSet="UTF-8" />
        <meta
          name="viewport"
          content="width=device-width, initial-scale=1, viewport-fit=cover"
        />
      </Head>
      <FacebookPixel />
      //…
      <main className="routesContainer">
        <Component siteData={siteData} {...pageProps} />
      </main>
      //…
    </>
  );
}

or in case you're using Class components, insert this in you componentDidMount() inside the App class:

  componentDidMount() {

    import('react-facebook-pixel')
      .then((x) => x.default)
      .then((ReactPixel) => {
        ReactPixel.init('Pixel ID Here');
        ReactPixel.pageView();

        Router.events.on('routeChangeComplete', () => {
          ReactPixel.pageView();
        });
      });
  }

font: https://github.com/zsajjad/react-facebook-pixel/issues/53

Frederiko Ribeiro
  • 1,844
  • 1
  • 18
  • 30
5

Simple and easy:

Put the below code inside _app.js:

useEffect(async () => {
        const { default: ReactPixel } = await import('react-facebook-pixel');
        ReactPixel.init(FB_PIXEL, null, {
            autoConfig: true,
            debug: true,
          });
        ReactPixel.pageView();
        ReactPixel.track("ViewContent")
    });
guneetgstar
  • 621
  • 7
  • 15