Facebook Pixel with NextJS?
Unanswered
Briquet Griffon Vendéen posted this in #help-forum
Briquet Griffon VendéenOP
Hey, how can I use the facebook pixel with nextJS. I am still using the outdated pages directory.
I put this in my _app.ts:
But when I load the page, it doesn't show.
I put this in my _app.ts:
function MyApp({ Component, pageProps }: AppProps) {
const router = useRouter();
const pageview = () => {
//@ts-expect-error
window.fbq("track", "PageView");
};
// https://developers.facebook.com/docs/facebook-pixel/advanced/
const event = (name: string, options = {}) => {
//@ts-expect-error
window.fbq("track", name, options);
};
useEffect(() => {
// This pageview only triggers the first time (it's important for Pixel to have real information)
console.log("recording page view");
pageview();
const handleRouteChange = () => {
pageview();
};
router.events.on("routeChangeComplete", handleRouteChange);
return () => {
router.events.off("routeChangeComplete", handleRouteChange);
};
}, [router.events]);
return (
<div className={raleway.className}>
<Script
id="fb-pixel"
strategy="afterInteractive"
dangerouslySetInnerHTML={{
__html: `
!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', ${process.env.NEXT_PUBLIC_FACEBOOK_PIXEL_ID!});
fbq('track', 'PageView');
`,
}}
/>
);
}
export default MyApp;But when I load the page, it doesn't show.