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

@adkit.so/meta-pixel-nuxt

Package Overview
Dependencies
Maintainers
1
Versions
8
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@adkit.so/meta-pixel-nuxt

Nuxt 3 & 4 module for Meta Pixel tracking, built on top of @adkit.so/meta-pixel

latest
Source
npmnpm
Version
1.0.9
Version published
Maintainers
1
Created
Source

Meta Pixel for Nuxt

npm version npm downloads License: MIT

The most powerful and developer-friendly Meta Pixel integration for Nuxt 3 & 4.

Built on top of @adkit.so/meta-pixel, this module provides a seamless, type-safe Meta Pixel experience with advanced features like route control, event deduplication, and beautiful debug logging.

📚 Table of Contents

✨ Features

  • Typescript Support - Full TypeScript support with autocomplete for all official events and parameters
  • 🎨 Auto-imported Composable - useMetaPixel() available everywhere, zero boilerplate
  • 🎯 Custom Events Support - Track custom events with full type safety and flexible data structures
  • 🛣️ Advanced Route Control - Granular control on where to enable or disable tracking
  • 🚦 Event Deduplication - Support for preventing duplicate events with event IDs
  • 🔌 Multiple Pixels Support - Load and manage multiple pixel IDs effortlessly

⚡ Quick Start

npx nuxi@latest module add @adkit.so/meta-pixel-nuxt

OR

npm install @adkit.so/meta-pixel-nuxt
export default defineNuxtConfig({
    modules: ['@adkit.so/meta-pixel-nuxt'],
    metaPixel: {
        pixelIds: 'YOUR_PIXEL_ID',
    },
});
<template>
    <button @click="handlePurchase">Complete Purchase</button>
</template>

<script setup>
    const meta = useMetaPixel();

    const handlePurchase = () => {
        meta.track('Purchase', {
            value: 99.99,
            currency: 'USD',
        });
    };
</script>

That's it! 🎉

📦 Installation

npx nuxi@latest module add @adkit.so/meta-pixel-nuxt
npm install @adkit.so/meta-pixel-nuxt

⚙️ Configuration

Basic Setup

Add the module to your nuxt.config.ts:

export default defineNuxtConfig({
    modules: ['@adkit.so/meta-pixel-nuxt'],

    metaPixel: {
        pixelIds: 'YOUR_PIXEL_ID', // or array ['PIXEL_1', 'PIXEL_2']
        autoTrackPageView: true, // default: true
        debug: true, // Enable debug logs (default: false)
        enableLocalhost: true, // Enable on localhost (default: false)
    },
});

Configuration Options

OptionTypeDefaultDescription
pixelIdsstring | string[]''Required. Single pixel ID or array of pixel IDs
autoTrackPageViewbooleantrueAutomatically track PageView on initialization
debugbooleanfalseEnable styled console logs with background colors
enableLocalhostbooleanfalseEnable tracking on localhost (useful for testing)
excludedRoutesstring[][]Array of glob patterns to exclude from tracking (e.g., /dashboard/**)
includedRoutesstring[][]Array of glob patterns to whitelist (only these routes will be tracked)

Multiple Pixels Example

// nuxt.config.ts
export default defineNuxtConfig({
    metaPixel: {
        pixelIds: ['PIXEL_ID_1', 'PIXEL_ID_2', 'PIXEL_ID_3'],
        autoTrackPageView: true,
    },
});

💡 Usage

The useMetaPixel() composable is auto-imported and ready to use anywhere in your Nuxt app. It provides direct access to the Meta Pixel instance with all methods from @adkit.so/meta-pixel.

Basic Usage

<!-- index.vue -->
<template>
    <button @click="meta.track('AddToCart', { value: 29.99, currency: 'USD' })">Add to Cart</button>
</template>

<script setup>
    const meta = useMetaPixel();

    // Track standard events
    meta.track('Purchase', {
        value: 99.99,
        currency: 'USD',
        content_ids: ['SKU_123'],
    });

    // Track custom events
    meta.trackCustom('MyCustomEvent', {
        custom_param: 'value',
    });
</script>

With Event Deduplication

<!-- index.vue -->
<template>
    <button @click="handleCheckout">Checkout</button>
</template>

<script setup>
    const meta = useMetaPixel();

    const handleCheckout = () => {
        meta.track(
            'InitiateCheckout',
            {
                value: 149.99,
                currency: 'USD',
                num_items: 3,
            },
            {
                eventID: `checkout-${Date.now()}`,
            },
        );
    };
</script>

Check if Pixel is Loaded

<!-- index.vue -->
<template>
    <button @click="trackIfReady">Track Purchase</button>
</template>

<script setup>
    const meta = useMetaPixel();

    const trackIfReady = () => {
        if (meta.isLoaded()) {
            meta.track('Purchase', { value: 99.99, currency: 'USD' });
        }
    };
</script>

🛣️ Route Control

You can control where the pixel is loaded using three methods:

1. Exclude Routes (Global)

In nuxt.config.ts, provide an array of glob patterns to exclude specific routes:

// nuxt.config.ts
export default defineNuxtConfig({
    metaPixel: {
        pixelIds: '...',

        excludedRoutes: [
            '/dashboard/*', // Excludes /dashboard/inbox, /dashboard/settings (one level)
            '/dashboard/**', // Excludes /dashboard and ALL nested routes (any depth)
            '/admin/**', // Excludes /admin and all nested routes
            '/api/*', // Excludes /api/users, /api/posts (one level only)
        ],
    },
});

Pattern Syntax:

  • * - Matches any characters except / (single path segment)
  • ** - Matches any characters including / (multiple path segments, any depth)

Examples:

  • /dashboard/* → Excludes /dashboard/inbox but NOT /dashboard/inbox/messages
  • /dashboard/** → Excludes /dashboard, /dashboard/inbox, /dashboard/inbox/messages, etc. (any depth)
  • /api/* → Excludes /api/users but NOT /api/users/123

2. Include Routes (Global)

If you only want to track specific sections, use includedRoutes. This takes precedence over excluded routes (except for page-level overrides).

// nuxt.config.ts
export default defineNuxtConfig({
    metaPixel: {
        pixelIds: '...',

        includedRoutes: [
            '/shop/**', // Track all shop pages (any depth)
            '/checkout/**', // Track all checkout pages (any depth)
            '/product/*', // Track product pages (one level only)
        ],
    },
});

3. Page-Level Control

You can enable or disable the pixel on a per-page basis using definePageMeta:

<template>
    <div>Secret page - no tracking here</div>
</template>

<script setup>
    definePageMeta({
        metaPixel: false,
    });
</script>

Priority Order:

  • Page-level definePageMeta (highest priority)
  • includedRoutes (if set, only these are tracked)
  • excludedRoutes (if set, these are ignored)
  • Default: Track everything

🌍 Environment Variables

You can configure pixel IDs via environment variables instead of hardcoding them in nuxt.config.ts. This is especially useful for different environments (dev, staging, production).

# .env
META_PIXEL_ID=123456789012345

Then reference it in your config:

// nuxt.config.ts
export default defineNuxtConfig({
    metaPixel: {
        pixelIds: process.env.META_PIXEL_ID || '',
    },
});

Multiple Pixels via Environment Variables

# .env
META_PIXEL_DEFAULT=123456789012345
META_PIXEL_BACKUP=987654321098765
export default defineNuxtConfig({
    metaPixel: {
        pixelIds: [process.env.META_PIXEL_DEFAULT, process.env.META_PIXEL_BACKUP],
    },
});

🐛 Debug Mode

When debug: true, you'll see beautiful styled console logs:

  • 🔵 [Meta Pixel] Info messages (blue background)
  • [Meta Pixel] Success messages (green background)
  • ⚠️ [Meta Pixel] Warning messages (orange background)

Example output:

[Meta Pixel] Initializing Meta Pixel... { pixelIds: [...], autoTrackPageView: true }
[Meta Pixel] ✓ Meta Pixel initialized successfully
[Meta Pixel] Tracking standard event: "Purchase" { data: {...}, eventData: {...} }

📊 Standard Events

All Meta Pixel standard events are supported with full TypeScript autocomplete. These events help you track important actions on your website and optimize your ad campaigns.

EventDescriptionCommon Use Cases
AddPaymentInfoPayment info addedCheckout flow
AddToCartItem added to shopping cartE-commerce
AddToWishlistItem added to wishlistE-commerce
CompleteRegistrationUser completed registrationSign-ups, account creation
ContactUser contacted businessContact forms
CustomizeProductProduct customization startedProduct configurators
DonateDonation madeNon-profits
FindLocationLocation finder usedStore locators
InitiateCheckoutCheckout process startedE-commerce funnels
LeadLead submittedLead generation forms
PurchasePurchase completedTransaction confirmation
ScheduleAppointment scheduledBooking systems
SearchSearch performedSite search
StartTrialTrial startedSaaS applications
SubmitApplicationApplication submittedJob boards, loan applications
SubscribeSubscription startedNewsletters, subscriptions
ViewContentContent viewedProduct pages, blog posts

You can find the official list of standard events here.

Example Usage

<template>
    <div>
        <button @click="trackPurchase">Complete Purchase</button>
        <button @click="trackLead">Submit Lead</button>
        <input @input="trackSearch($event.target.value)" placeholder="Search..." />
    </div>
</template>

<script setup>
    const meta = useMetaPixel();

    const trackPurchase = () => {
        meta.track('Purchase', {
            value: 299.99,
            currency: 'USD',
            content_ids: ['SKU_12345'],
            content_type: 'product',
            num_items: 1,
        });
    };

    const trackLead = () => {
        meta.track('Lead', {
            content_name: 'Newsletter Signup',
            content_category: 'Marketing',
        });
    };

    const trackSearch = (query: string) => {
        meta.track('Search', {
            search_string: query,
        });
    };
</script>

📋 Event Data Parameters

All event parameters are optional but help improve ad targeting and conversion tracking. Here are the most common ones:

ParameterTypeDescriptionExample
valuenumberMonetary value of the event99.99
currencystringISO 4217 currency code'USD', 'EUR', 'GBP'
content_idsstring[]Product IDs or SKUs['SKU_123', 'SKU_456']
content_typestringType of content'product', 'product_group'
content_namestringName of page/product'Blue T-Shirt'
content_categorystringCategory of page/product'Apparel', 'Electronics'
contentsArray<{id, quantity}>Detailed product information[{id: 'SKU_123', quantity: 2}]
num_itemsnumberNumber of items3
search_stringstringSearch query'running shoes'
statusbooleanRegistration/subscription statustrue
predicted_ltvnumberPredicted lifetime value of customer450.00

Complete E-commerce Example

<template>
    <div>
        <h1>{{ product.name }}</h1>
        <p>${{ product.price }}</p>
        <button @click="trackAddToCart">Add to Cart</button>
        <button @click="trackPurchase('order-123')">Buy Now</button>
    </div>
</template>

<script setup>
    const meta = useMetaPixel();

    const product = {
        id: 'SKU_789',
        name: 'Wireless Headphones',
        price: 149.99,
        category: 'Electronics',
    };

    onMounted(() => {
        trackProductView();
    });

    const trackProductView = () => {
        meta.track('ViewContent', {
            content_ids: [product.id],
            content_type: 'product',
            content_name: product.name,
            content_category: product.category,
            value: product.price,
            currency: 'USD',
        });
    };

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

    const trackPurchase = (orderId: string) => {
        meta.track(
            'Purchase',
            {
                content_ids: [product.id],
                content_type: 'product',
                value: product.price,
                currency: 'USD',
                num_items: 1,
            },
            {
                eventID: orderId,
            },
        );
    };
</script>

🚀 Advanced Usage

Custom Events

Track custom events specific to your business:

<template>
    <div>
        <button @click="trackPricingView">View Pricing</button>
        <video @ended="trackVideoComplete">Your video</video>
    </div>
</template>

<script setup>
    const meta = useMetaPixel();

    const trackPricingView = () => {
        meta.trackCustom('PricingPageViewed', {
            plan: 'enterprise',
            duration: 'annual',
        });
    };

    const trackVideoComplete = () => {
        meta.trackCustom('VideoWatched', {
            video_id: 'intro_2024',
            watch_percentage: 100,
        });
    };
</script>

Event Deduplication

Prevent duplicate event tracking by using unique event IDs. This is crucial when tracking conversions from both client and server:

<script setup>
    const meta = useMetaPixel();

    const processOrder = async (orderId: string) => {
        // Use order ID as event ID to prevent duplicates
        meta.track(
            'Purchase',
            {
                value: 299.99,
                currency: 'USD',
                content_ids: ['SKU_123'],
            },
            {
                eventID: `order-${orderId}`,
            },
        );

        // Even if this fires multiple times or from server too,
        // Meta will deduplicate based on eventID
    };
</script>

Conditional Tracking

<script setup>
    const meta = useMetaPixel();
    const userStore = useUserStore();

    const trackWithUserContext = () => {
        // Only track if pixel is loaded
        if (!meta.isLoaded()) {
            console.warn('Meta Pixel not loaded yet');
            return;
        }

        // Add user context to events
        meta.track('CompleteRegistration', {
            status: true,
            content_name: userStore.accountType,
        });
    };
</script>

📝 TypeScript Support

Full type safety with exported types:

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

const meta = useMetaPixel();

const trackEvent = (event: StandardEvent, data: EventData) => {
    meta.track(event, data);
};

All methods, events, and parameters have complete TypeScript definitions with IntelliSense support in your IDE.

❓ Troubleshooting

Pixel not loading?

  • Check your pixel ID - Make sure it's correct in your config
  • Enable debug mode - Set debug: true to see detailed logs
  • Check browser console - Look for errors or warnings
  • Verify route isn't excluded - Check your excludedRoutes config
  • Enable on localhost - Set enableLocalhost: true for local testing

Route exclusion not working?

If your routes aren't being excluded properly:

  • Use glob patterns - For most cases, glob patterns are easier:

    excludedRoutes: ['/dashboard/**']; // ✅ Correct - excludes all dashboard routes
    
  • Common mistakes to avoid:

    // ❌ Wrong - missing leading slash
    excludedRoutes: ['dashboard/**'];
    
    // ✅ Correct - with leading slash
    excludedRoutes: ['/dashboard/**'];
    
  • Enable debug mode to see which routes are being excluded:

    metaPixel: {
        debug: true,  // Will log "Route excluded: /dashboard/inbox"
        excludedRoutes: ['/dashboard/**'],
    }
    
  • Pattern examples:

    • /dashboard/* - Excludes /dashboard/inbox but NOT /dashboard/inbox/messages
    • /dashboard/** - Excludes /dashboard, /dashboard/inbox, /dashboard/inbox/messages, etc. (any depth)

Events not showing in Meta Events Manager?

  • Wait a few minutes - Events can take 5-20 minutes to appear
  • Check Test Events - Use the Test Events tool in Meta Events Manager
  • Verify event names - Standard events are case-sensitive
  • Use event deduplication - Add unique eventID to prevent duplicates
  • Check ad blockers - Some extensions block Meta Pixel

TypeScript errors?

Make sure you have the latest version:

npm update @adkit.so/meta-pixel-nuxt

Multiple pixels not working?

// ✅ Correct
metaPixel: {
    pixelIds: ['ID_1', 'ID_2'],
}

// ❌ Incorrect
metaPixel: {
    pixelIds: 'ID_1,ID_2',
}

📖 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

Learn more about Meta Pixel from official Facebook resources:

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

📄 License

MIT

Made with ❤️ by Adkit

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

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