Logo
Published on 4/19/2025

Integrating Meta Pixel in a Next.js Application with the App Directory

How to Add Meta Pixel to a Next.js 13 App (App Directory)

Meta Pixel (formerly Facebook Pixel) lets you track events like page views, button clicks, and purchases — crucial for running ads and remarketing on Facebook/Instagram.

Steps to Integrate Meta Pixel:

1. Get Your Pixel ID

Head to Meta Business Manager → Events Manager → Pixels → Copy your Pixel ID.

2. Create a Component

In your Next.js 13 project, create this component inside components/common/PixelTracker.tsx:


// components/common/PixelTracker.tsx
'use client';
import Script from 'next/script';

const PixelTracker = () => {
  return (
    <>
      {/* Meta Pixel Script */}
      <Script
        id="meta-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', 'YOUR_PIXEL_ID');
            fbq('track', 'PageView');
          `,
        }}
      />

      {/* Fallback for no JS */}
      <noscript>
        <img
          height="1"
          width="1"
          style={{ display: 'none' }}
          src="https://www.facebook.com/tr?id=YOUR_PIXEL_ID&ev=PageView&noscript=1"
          alt=""
        />
      </noscript>
    </>
  );
};

export default PixelTracker;

3. Use It in Your Layout

Edit your global layout file app/layout.tsx and add the component:


// app/layout.tsx
import './globals.css'
import { ReactNode } from 'react'
import PixelTracker from '@/components/common/PixelTracker'

export default function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html lang="en">
      <body>
        <PixelTracker />
        {children}
      </body>
    </html>
  );
}

✅ Done!

Meta Pixel will now fire PageView events across your entire Next.js app using the App Directory.