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 🙏

© 2026 – Pkg Stats / Ryan Hefner

facebook-pixel-pro

v1.1.0

Published

Easy Facebook Pixel integration with Conversion API support. Just one function call and you're done!

Readme

Facebook Pixel Pro 🚀

Easy Facebook Pixel integration with Conversion API support. Just one function call and you're done!

npm version TypeScript License: MIT

✨ Features

  • 🎯 One-line setup - Initialize with just your Pixel ID
  • 🔄 Dual tracking - Browser pixel + server-side Conversion API
  • 🛡️ TypeScript support - Full type safety and IntelliSense
  • 🔧 Environment variables - Automatic config from env vars
  • 🚫 Deduplication - Prevents duplicate events automatically
  • 📊 Advanced matching - Enhanced user matching with hashed PII
  • 🎨 Framework agnostic - Works with React, Vue, Angular, vanilla JS
  • Performance optimized - Lightweight with smart debouncing
  • 🔍 Debug mode - Detailed logging for development

🚀 Quick Start

Installation

npm install facebook-pixel-pro
# or
yarn add facebook-pixel-pro
# or
pnpm add facebook-pixel-pro

Basic Usage

import { initFacebookPixel } from 'facebook-pixel-pro';

// Initialize with just your Pixel ID
const pixel = initFacebookPixel({
  pixelId: 'your-pixel-id'
});

// That's it! PageView is tracked automatically
// All standard events are ready to use

With Environment Variables (Recommended)

import { initWithEnv } from 'facebook-pixel-pro';

// Reads from FACEBOOK_PIXEL_ID and FACEBOOK_ACCESS_TOKEN env vars
const pixel = initWithEnv();

Set these environment variables:

# Required
FACEBOOK_PIXEL_ID=your-pixel-id

# Optional (for Conversion API)
FACEBOOK_ACCESS_TOKEN=your-conversion-api-token
FACEBOOK_TEST_EVENT_CODE=your-test-event-code

📚 Documentation

Configuration Options

interface FacebookPixelConfig {
  /** Facebook Pixel ID (required) */
  pixelId: string;
  
  /** Facebook Conversion API Access Token (optional) */
  accessToken?: string;
  
  /** Test Event Code for testing (optional) */
  testEventCode?: string;
  
  /** Enable automatic PageView tracking (default: true) */
  autoPageView?: boolean;
  
  /** Enable server-side Conversion API (default: true if accessToken provided) */
  enableConversionApi?: boolean;
  
  /** Debug mode for additional logging (default: false) */
  debug?: boolean;
}

Tracking Events

ViewContent

await pixel.trackViewContent({
  content_name: 'Product Name',
  content_category: 'Category',
  content_ids: ['product-123'],
  value: 29.99,
  currency: 'USD'
});

Purchase

await pixel.trackPurchase({
  value: 99.99,
  currency: 'USD',
  content_ids: ['product-123', 'product-456'],
  contents: ['Product 1', 'Product 2'],
  num_items: 2
});

Add to Cart

await pixel.trackAddToCart({
  value: 29.99,
  currency: 'USD',
  content_ids: ['product-123'],
  contents: ['Product Name'],
  num_items: 1
});

Initiate Checkout

await pixel.trackInitiateCheckout({
  value: 99.99,
  currency: 'USD',
  content_ids: ['product-123'],
  num_items: 2
});

Custom Events

await pixel.trackCustomEvent('CustomEventName', {
  custom_parameter: 'value',
  value: 50,
  currency: 'USD'
});

Advanced Features

Enhanced User Matching

Provide hashed user information for better ad attribution:

// Hash user data automatically
import { hashUserDetails } from 'facebook-pixel-pro';

const hashedData = await hashUserDetails({
  email: '[email protected]',
  phone: '+1234567890',
  firstName: 'John',
  lastName: 'Doe'
});

await pixel.trackPurchase({
  value: 99.99,
  currency: 'USD',
  content_ids: ['product-123'],
  userInfo: hashedData
});

Event Deduplication

Prevent duplicate events with unique event IDs:

const eventId = `purchase_${Date.now()}_${Math.random()}`;

await pixel.trackPurchase({
  value: 99.99,
  currency: 'USD',
  content_ids: ['product-123'],
  event_id: eventId
});

Test Server API Connection

const result = await pixel.testServerApi();
console.log('Server API status:', result.success);

🛠️ Framework Examples

React/Next.js

// pages/_app.tsx or app/layout.tsx
import { initWithEnv } from 'facebook-pixel-pro';

const pixel = initWithEnv();

export default function App({ Component, pageProps }) {
  return <Component {...pageProps} />;
}

// In your components
import { useEffect } from 'react';

function ProductPage({ product }) {
  useEffect(() => {
    pixel.trackViewContent({
      content_name: product.name,
      content_category: product.category,
      content_ids: [product.id],
      value: product.price,
      currency: 'USD'
    });
  }, [product]);

  const handlePurchase = () => {
    pixel.trackPurchase({
      value: product.price,
      currency: 'USD',
      content_ids: [product.id]
    });
  };

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

Vue.js

// main.ts
import { createApp } from 'vue';
import { initWithEnv } from 'facebook-pixel-pro';

const app = createApp(App);
const pixel = initWithEnv();

app.config.globalProperties.$pixel = pixel;
<!-- Product.vue -->
<template>
  <div>
    <h1>{{ product.name }}</h1>
    <button @click="handlePurchase">Buy Now</button>
  </div>
</template>

<script>
export default {
  props: ['product'],
  mounted() {
    this.$pixel.trackViewContent({
      content_name: this.product.name,
      content_category: this.product.category,
      content_ids: [this.product.id],
      value: this.product.price,
      currency: 'USD'
    });
  },
  methods: {
    handlePurchase() {
      this.$pixel.trackPurchase({
        value: this.product.price,
        currency: 'USD',
        content_ids: [this.product.id]
      });
    }
  }
};
</script>

Vanilla JavaScript

<!DOCTYPE html>
<html>
<head>
    <script src="https://unpkg.com/facebook-pixel-pro/dist/index.umd.js"></script>
</head>
<body>
    <script>
        const pixel = FacebookPixelPro.initFacebookPixel({
            pixelId: 'your-pixel-id',
            debug: true
        });

        // Track events
        pixel.trackViewContent({
            content_name: 'Product Name',
            content_category: 'Category',
            content_ids: ['product-123'],
            value: 29.99,
            currency: 'USD'
        });
    </script>
</body>
</html>

🔧 Server-Side Setup (Optional)

For server-side Conversion API tracking, you need to set up an endpoint:

Next.js API Route Example

// pages/api/facebook.ts or app/api/facebook/route.ts
import { NextApiRequest, NextApiResponse } from 'next';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  const { eventName, eventData, userData } = req.body;

  try {
    // Send to Facebook Conversion API
    const response = await fetch(`https://graph.facebook.com/v18.0/${process.env.FACEBOOK_PIXEL_ID}/events`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        data: [{
          event_name: eventName,
          event_time: Math.floor(Date.now() / 1000),
          action_source: 'website',
          user_data: userData,
          custom_data: eventData,
          event_source_url: req.headers.referer || '',
        }],
        access_token: process.env.FACEBOOK_ACCESS_TOKEN,
        test_event_code: process.env.FACEBOOK_TEST_EVENT_CODE
      })
    });

    const result = await response.json();
    res.status(200).json(result);
  } catch (error) {
    console.error('Facebook Conversion API error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
}

🔍 Debugging

Enable debug mode to see detailed logs:

const pixel = initFacebookPixel({
  pixelId: 'your-pixel-id',
  debug: true // Enable debug logging
});

// Check browser console for detailed logs

🛡️ Privacy & Compliance

  • ✅ Automatically hashes PII (emails, phone numbers, names)
  • ✅ Respects user consent (implement your own consent logic)
  • ✅ Cleans tracking parameters from URLs
  • ✅ Secure cookie handling
  • ✅ GDPR/CCPA friendly (with proper consent management)

GDPR Compliance Example

// Only initialize after user consent
if (userHasConsented) {
  const pixel = initFacebookPixel({
    pixelId: 'your-pixel-id'
  });
}

🚀 Performance

  • Lightweight: ~15KB gzipped
  • Smart debouncing: Prevents duplicate events
  • Lazy loading: Pixel script loaded only when needed
  • Async tracking: Non-blocking event tracking
  • Efficient bundling: Tree-shakeable exports

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

📄 License

MIT License - see the LICENSE file for details.

🆘 Support

🙏 Acknowledgments

  • Facebook Marketing API documentation
  • Meta Conversion API best practices
  • Community feedback and contributions

Made with ❤️ for developers who want Facebook Pixel integration to just work.