New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details
Socket
Book a DemoSign in
Socket

@adkit.so/meta-pixel-next

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@adkit.so/meta-pixel-next

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

latest
Source
npmnpm
Version
1.0.1
Version published
Maintainers
1
Created
Source

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

PropTypeDefaultDescription
pixelIdstring | string[]-Your Meta Pixel ID(s). Falls back to NEXT_PUBLIC_META_PIXEL_ID env var
debugbooleanfalseEnable styled console logging
enableLocalhostbooleanfalseEnable tracking on localhost (for testing)
autoTrackPageViewbooleantrueAuto 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:

EventDescriptionCommon Use Cases
PageViewAuto-tracked on route changes-
ViewContentContent/product viewedProduct pages
SearchSearch performedSite search
AddToCartItem added to cartE-commerce
AddToWishlistItem added to wishlistE-commerce
InitiateCheckoutCheckout startedCart page
AddPaymentInfoPayment info addedCheckout flow
PurchasePurchase completedOrder confirmation
LeadLead form submittedContact forms
CompleteRegistrationRegistration completedSign-up flows
ContactContact actionContact page
ScheduleAppointment scheduledBooking systems
StartTrialTrial startedSaaS apps
SubscribeSubscription startedNewsletters

Event Data Parameters

ParameterTypeDescriptionExample
valuenumberMonetary value99.99
currencystringISO 4217 currency code'USD', 'EUR'
content_idsstring[]Product IDs or SKUs['SKU_123']
content_typestringType of content'product'
content_namestringName of product/page'Blue T-Shirt'
content_categorystringCategory'Apparel'
num_itemsnumberNumber of items3
search_stringstringSearch 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?

  • Check your pixel ID - Verify it's correct
  • Enable debug mode - Set debug={true} to see logs
  • Enable localhost - Set enableLocalhost={true} for local testing
  • 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!

Keywords

meta

FAQs

Package last updated on 26 Nov 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts