npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@adkit.so/meta-pixel-next

v1.0.1

Published

Next.js integration for Meta Pixel tracking - auto PageView on route changes

Downloads

214

Readme

Meta Pixel for Next.js

npm version npm downloads License: MIT

The simplest Meta Pixel integration for Next.js — with automatic PageView tracking on route changes.

Built on top of @adkit.so/meta-pixel-react, this package provides a drop-in component that handles everything automatically.

📚 Table of Contents

✨ Features

  • Auto PageView on Route Changes - No manual tracking needed for navigation
  • 🎯 Simple Drop-in Component - Just wrap your app with <MetaPixel />
  • 🔧 Environment Variable Support - Use NEXT_PUBLIC_META_PIXEL_ID out of the box
  • 📘 TypeScript Support - Full type definitions with autocomplete
  • 🚀 App Router Ready - Works with Next.js 13+ App Router
  • 🔌 Multiple Pixels Support - Track to multiple pixel IDs effortlessly

⚡ Quick Start

npm install @adkit.so/meta-pixel-next

Add <MetaPixel /> to your root layout:

// app/layout.tsx
import { MetaPixel } from '@adkit.so/meta-pixel-next';

export default function RootLayout({ children }: { children: React.ReactNode }) {
    return (
        <html>
            <body>
                <MetaPixel pixelId="YOUR_PIXEL_ID">{children}</MetaPixel>
            </body>
        </html>
    );
}

Track events in any component:

'use client';

import { useMetaPixel } from '@adkit.so/meta-pixel-next';

export function PurchaseButton() {
    const meta = useMetaPixel();

    function handlePurchase() {
        meta.track('Purchase', { value: 99.99, currency: 'USD' });
    }

    return <button onClick={handlePurchase}>Buy Now</button>;
}

That's it! 🎉

⚙️ Configuration

Component Props

| Prop | Type | Default | Description | | ------------------- | -------------------- | ------- | ------------------------------------------------------------------------ | | pixelId | string \| string[] | - | Your Meta Pixel ID(s). Falls back to NEXT_PUBLIC_META_PIXEL_ID env var | | debug | boolean | false | Enable styled console logging | | enableLocalhost | boolean | false | Enable tracking on localhost (for testing) | | autoTrackPageView | boolean | true | Auto track PageView on initial load and route changes |

Using Environment Variables

Instead of passing pixelId as a prop, use an environment variable:

# .env.local
NEXT_PUBLIC_META_PIXEL_ID=123456789012345
// app/layout.tsx
import { MetaPixel } from '@adkit.so/meta-pixel-next';

export default function RootLayout({ children }: { children: React.ReactNode }) {
    return (
        <html>
            <body>
                <MetaPixel debug={true} enableLocalhost={true}>
                    {children}
                </MetaPixel>
            </body>
        </html>
    );
}

Multiple Pixels

Track to multiple pixels simultaneously:

<MetaPixel pixelId={['PIXEL_ID_1', 'PIXEL_ID_2', 'PIXEL_ID_3']}>{children}</MetaPixel>

Or via environment variable (comma-separated):

NEXT_PUBLIC_META_PIXEL_ID=PIXEL_1,PIXEL_2

💡 Manual Event Tracking

Use the useMetaPixel hook in any client component:

'use client';

import { useMetaPixel } from '@adkit.so/meta-pixel-next';

export function ProductPage({ product }) {
    const meta = useMetaPixel();

    function handleAddToCart() {
        meta.track('AddToCart', {
            content_ids: [product.id],
            content_name: product.name,
            value: product.price,
            currency: 'USD',
        });
    }

    function handlePurchase() {
        meta.track('Purchase', {
            content_ids: [product.id],
            value: product.price,
            currency: 'USD',
            num_items: 1,
        });
    }

    return (
        <div>
            <h1>{product.name}</h1>
            <button onClick={handleAddToCart}>Add to Cart</button>
            <button onClick={handlePurchase}>Buy Now</button>
        </div>
    );
}

Custom Events

Track custom events specific to your business:

const meta = useMetaPixel();

function trackPricingView() {
    meta.trackCustom('PricingViewed', {
        plan: 'enterprise',
        source: 'homepage_cta',
    });
}

function trackVideoComplete() {
    meta.trackCustom('VideoWatched', {
        video_id: 'intro_2024',
        watch_percentage: 100,
    });
}

Event Deduplication

Prevent duplicate events using eventID:

function handleCheckout(orderId: string) {
    meta.track('Purchase', { value: 299.99, currency: 'USD' }, { eventID: `order-${orderId}` });
}

📊 Standard Events

All Meta Pixel standard events are supported with full TypeScript autocomplete:

| Event | Description | Common Use Cases | | ---------------------- | --------------------------------- | ------------------ | | PageView | Auto-tracked on route changes | - | | ViewContent | Content/product viewed | Product pages | | Search | Search performed | Site search | | AddToCart | Item added to cart | E-commerce | | AddToWishlist | Item added to wishlist | E-commerce | | InitiateCheckout | Checkout started | Cart page | | AddPaymentInfo | Payment info added | Checkout flow | | Purchase | Purchase completed | Order confirmation | | Lead | Lead form submitted | Contact forms | | CompleteRegistration | Registration completed | Sign-up flows | | Contact | Contact action | Contact page | | Schedule | Appointment scheduled | Booking systems | | StartTrial | Trial started | SaaS apps | | Subscribe | Subscription started | Newsletters |

Event Data Parameters

| Parameter | Type | Description | Example | | ------------------ | ---------- | ---------------------- | ----------------- | | value | number | Monetary value | 99.99 | | currency | string | ISO 4217 currency code | 'USD', 'EUR' | | content_ids | string[] | Product IDs or SKUs | ['SKU_123'] | | content_type | string | Type of content | 'product' | | content_name | string | Name of product/page | 'Blue T-Shirt' | | content_category | string | Category | 'Apparel' | | num_items | number | Number of items | 3 | | search_string | string | Search query | 'running shoes' |

🚀 Advanced Usage

Complete E-commerce Example

'use client';

import { useMetaPixel } from '@adkit.so/meta-pixel-next';
import { useEffect } from 'react';

export function ProductPage({ product }) {
    const meta = useMetaPixel();

    useEffect(() => {
        // Track product view on page load
        meta.track('ViewContent', {
            content_ids: [product.id],
            content_type: 'product',
            content_name: product.name,
            content_category: product.category,
            value: product.price,
            currency: 'USD',
        });
    }, [product.id]);

    function handleAddToCart() {
        meta.track('AddToCart', {
            content_ids: [product.id],
            content_type: 'product',
            content_name: product.name,
            value: product.price,
            currency: 'USD',
        });
    }

    function handlePurchase(orderId: string) {
        meta.track(
            'Purchase',
            {
                content_ids: [product.id],
                content_type: 'product',
                value: product.price,
                currency: 'USD',
                num_items: 1,
            },
            { eventID: orderId }, // For deduplication
        );
    }

    return (
        <div>
            <h1>{product.name}</h1>
            <p>${product.price}</p>
            <button onClick={handleAddToCart}>Add to Cart</button>
            <button onClick={() => handlePurchase('order-123')}>Buy Now</button>
        </div>
    );
}

Disable Auto PageView Tracking

If you prefer to handle PageView tracking manually:

<MetaPixel pixelId="YOUR_PIXEL_ID" autoTrackPageView={false}>
    {children}
</MetaPixel>

Check if Pixel is Loaded

function trackIfReady() {
    if (meta.isLoaded()) {
        meta.track('Purchase', { value: 99.99, currency: 'USD' });
    }
}

📘 TypeScript

Full TypeScript support with exported types:

import type { StandardEvent, EventData, EventMetaData } from '@adkit.so/meta-pixel-next';

function trackEvent(event: StandardEvent, data: EventData) {
    meta.track(event, data);
}

🐛 Debug Mode

Enable debug={true} to see styled console logs:

[Meta Pixel] Initializing Meta Pixel... { pixelIds: [...] }
[Meta Pixel] ✓ Meta Pixel initialized successfully
[Meta Pixel] Tracking: PageView
[Meta Pixel Next.js] Auto-tracking PageView on route change: /about

❓ Troubleshooting

Pixel not loading?

  1. Check your pixel ID - Verify it's correct
  2. Enable debug mode - Set debug={true} to see logs
  3. Enable localhost - Set enableLocalhost={true} for local testing
  4. Check browser console - Look for errors

PageView not tracking on route changes?

Make sure <MetaPixel /> wraps your content in the root layout, not a nested layout.

Events not showing in Meta Events Manager?

  • Wait 5-20 minutes - Events can take time to appear
  • Use Test Events tool - In Meta Events Manager
  • Check ad blockers - They can block the pixel

Using React without Next.js?

Use @adkit.so/meta-pixel-react instead. Note: auto PageView on route changes requires manual setup with React Router.

📖 Full Guide

For a complete step-by-step guide on installing and configuring Meta Pixel, check out our detailed tutorial:

How to Install Meta Pixel

📚 Official Documentation

📄 License

MIT


Made with ❤️ by Adkit

If this package helped you, please consider giving it a ⭐️ on GitHub!