HubSpot Meta Pixel Integration
Complete guide to setting up Meta Pixel (Facebook Pixel) on your HubSpot CMS and Marketing Hub for conversion tracking, lead generation, and audience building.
Overview
Meta Pixel (formerly Facebook Pixel) is a powerful analytics tool that tracks visitor actions on your HubSpot website and landing pages. This integration enables sophisticated advertising campaigns on Facebook and Instagram while leveraging HubSpot's robust CRM and marketing automation capabilities.
Why Meta Pixel for HubSpot?
Combining Meta Pixel with HubSpot creates a powerful marketing stack:
- Unified Lead Tracking: Connect Facebook ad clicks to HubSpot contacts
- CRM-Powered Audiences: Build custom audiences from HubSpot contact lists
- Form Conversion Tracking: Track HubSpot form submissions as conversions
- Landing Page Optimization: Measure performance of HubSpot landing pages
- Marketing Automation: Trigger workflows based on ad engagement
- Attribution: Understand the full customer journey from ad to customer
Installation Methods
Method 1: HubSpot Tracking Code (Recommended)
HubSpot provides a dedicated area for third-party tracking codes.
Installation Steps
- Get Your Pixel ID
Navigate to Facebook Events Manager:
- Select your pixel
- Copy the Pixel ID (15-16 digit number)
- Copy the base pixel code
- Access HubSpot Settings
In your HubSpot account:
- Navigate to Settings (gear icon)
- Select Tracking & Analytics > Tracking Code
- Or visit:
https://app.hubspot.com/settings/[PORTAL_ID]/marketing/tracking/code
- Add Pixel Code
Scroll to Footer HTML section and paste:
<!-- Meta Pixel Code -->
<script>
!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');
</script>
<noscript>
<img height="1" width="1" style="display:none"
src="https://www.facebook.com/tr?id=YOUR_PIXEL_ID&ev=PageView&noscript=1"/>
</noscript>
<!-- End Meta Pixel Code -->
- Publish Changes
Click Save to apply across all HubSpot-hosted pages.
Advantages
- Automatically applies to all HubSpot pages and landing pages
- No theme editing required
- Easy to manage and update
- Works with HubSpot drag-and-drop pages
Method 2: Google Tag Manager Integration
If you're using GTM with HubSpot, this provides more flexibility.
Prerequisites
- GTM installed on HubSpot (via Tracking Code settings)
- Access to GTM container
Implementation Steps
- Verify GTM Installation
Check that GTM is installed in HubSpot:
- Settings > Tracking & Analytics > Tracking Code
- Confirm GTM container ID is present
- Create Meta Pixel Tag in GTM
- Tags > New
- Tag Type: Custom HTML
- Tag Name: "Meta Pixel - Base Code"
<script>
!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');
</script>
- Trigger: All Pages
- Save and Submit container
- Configure HubSpot Variables
Create GTM variables to capture HubSpot data:
- Form ID: Custom JavaScript to extract form data
- Page type: Use URL patterns
- Contact properties: Via HubSpot API
Method 3: HubSpot CMS Theme Integration
For CMS Hub Professional/Enterprise with custom themes.
Implementation Steps
- Access Theme Files
In HubSpot:
- Navigate to Marketing > Files and Templates > Design Tools
- Select your theme
- Edit Base Template
Add pixel code to your base HTML template (usually base.html):
<!doctype html>
<html lang="{{ html_lang }}" {{ html_lang_dir }}>
<head>
<meta charset="utf-8">
<title>{{ page_meta.html_title }}</title>
{{ standard_header_includes }}
<!-- Meta Pixel Code -->
<script>
!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');
</script>
</head>
- Publish Theme
Publish changes to make them live.
Standard Events Implementation
PageView Event
Automatically tracked with base pixel. Enhanced with HubSpot context:
<script>
fbq('track', 'PageView', {
page_type: '{{ content.template_type }}',
content_id: '{{ content.id }}'
});
</script>
ViewContent Event
Track blog post and landing page views:
{% if content.template_type == "blog_post" %}
<script>
fbq('track', 'ViewContent', {
content_name: '{{ content.name }}',
content_category: '{{ content.blog_post_author }}',
content_ids: ['{{ content.id }}'],
content_type: 'blog_post'
});
</script>
{% endif %}
Lead Event - HubSpot Forms
Track form submissions using HubSpot's Forms API:
<script>
// Listen for HubSpot form submissions
window.addEventListener('message', function(event) {
if(event.data.type === 'hsFormCallback' && event.data.eventName === 'onFormSubmitted') {
fbq('track', 'Lead', {
content_name: event.data.data.formGuid || 'form_submission'
});
}
});
</script>
Alternative Form Tracking (jQuery)
For forms embedded via jQuery:
<script>
$(document).ready(function() {
window.addEventListener('message', function(event) {
if (event.data.type === 'hsFormCallback') {
if (event.data.eventName === 'onFormSubmit') {
fbq('track', 'Lead', {
form_id: event.data.id
});
}
}
});
});
</script>
CompleteRegistration Event
Track when leads convert to Marketing Qualified Leads (MQL):
<script>
// Track MQL conversions
// Requires HubSpot contact property integration
if ({{ contact.hs_lifecyclestage_lead_date }}) {
fbq('track', 'CompleteRegistration');
}
</script>
Schedule Event
Track meeting bookings via HubSpot Meetings:
<script>
// Listen for meeting bookings
window.addEventListener('message', function(event) {
if (event.data.meetingBookSucceeded) {
fbq('track', 'Schedule', {
content_name: 'Meeting Booked'
});
}
});
</script>
Purchase Event
For HubSpot Commerce Hub or custom checkout:
{% if content.template_type == "checkout_confirmation" %}
<script>
fbq('track', 'Purchase', {
value: {{ order.total }},
currency: 'USD',
content_ids: [{% for item in order.line_items %}'{{ item.sku }}'{% if not loop.last %},{% endif %}{% endfor %}],
content_type: 'product',
num_items: {{ order.line_items|length }}
});
</script>
{% endif %}
Advanced Matching with HubSpot Contacts
Improve attribution by sending hashed contact information:
<script>
{% if contact %}
// Hash contact email for better matching
async function hashValue(value) {
const encoder = new TextEncoder();
const data = encoder.encode(value.toLowerCase().trim());
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}
(async function() {
const hashedEmail = await hashValue('{{ contact.email }}');
const hashedFirstName = '{{ contact.firstname }}' ? await hashValue('{{ contact.firstname }}') : null;
const hashedLastName = '{{ contact.lastname }}' ? await hashValue('{{ contact.lastname }}') : null;
fbq('init', 'YOUR_PIXEL_ID', {
em: hashedEmail,
fn: hashedFirstName,
ln: hashedLastName,
ct: '{{ contact.city }}' ? await hashValue('{{ contact.city }}') : null,
st: '{{ contact.state }}' ? await hashValue('{{ contact.state }}') : null,
zp: '{{ contact.zip }}' ? await hashValue('{{ contact.zip }}') : null
});
})();
{% endif %}
</script>
Conversions API (Server-Side Tracking)
Implement CAPI for more reliable tracking with HubSpot workflows.
Prerequisites
- HubSpot Professional or Enterprise
- Access to HubSpot Workflows
- Webhook endpoint to receive HubSpot data
- Facebook Business SDK
Implementation
- Create Webhook Endpoint
Set up a server to receive HubSpot webhook data:
const express = require('express');
const bizSdk = require('facebook-nodejs-business-sdk');
const app = express();
app.use(express.json());
const access_token = process.env.FB_ACCESS_TOKEN;
const pixel_id = process.env.FB_PIXEL_ID;
const ServerEvent = bizSdk.ServerEvent;
const EventRequest = bizSdk.EventRequest;
const UserData = bizSdk.UserData;
const CustomData = bizSdk.CustomData;
bizSdk.FacebookAdsApi.init(access_token);
app.post('/webhooks/hubspot/form-submission', async (req, res) => {
try {
const submission = req.body;
const userData = (new UserData())
.setEmail(submission.submittedAt.email)
.setFirstName(submission.submittedAt.firstname)
.setLastName(submission.submittedAt.lastname)
.setCity(submission.submittedAt.city)
.setState(submission.submittedAt.state)
.setZipCode(submission.submittedAt.zip)
.setClientIpAddress(submission.context?.ipAddress)
.setClientUserAgent(submission.context?.userAgent);
const customData = (new CustomData())
.setContentName(submission.formGuid);
const serverEvent = (new ServerEvent())
.setEventName('Lead')
.setEventTime(Math.floor(submission.submittedAt / 1000))
.setUserData(userData)
.setCustomData(customData)
.setEventSourceUrl(submission.context?.pageUrl)
.setActionSource('website');
const eventsData = [serverEvent];
const eventRequest = (new EventRequest(access_token, pixel_id))
.setEvents(eventsData);
const response = await eventRequest.execute();
console.log('Conversion API response:', response);
res.status(200).send('Event sent');
} catch (error) {
console.error('Error:', error);
res.status(500).send('Error');
}
});
app.listen(3000, () => console.log('Webhook server running on port 3000'));
- Configure HubSpot Workflow
In HubSpot:
- Automation > Workflows > Create workflow
- Enrollment trigger: Form submission
- Action: Send a webhook
- URL: Your webhook endpoint
- Method: POST
- Include contact properties in request body
- Test Integration
Submit a test form and verify:
- Webhook receives data
- Conversion API receives event
- Event appears in Facebook Events Manager Test Events
HubSpot CRM List Syncing
Custom Audiences from HubSpot Lists
- Export HubSpot List
- Navigate to Contacts > Lists
- Select target list
- Export > Export all contacts
- Download CSV with email addresses
- Upload to Facebook
- Go to Facebook Ads Manager
- Audiences > Create Audience > Custom Audience
- Select Customer List
- Upload CSV file
- Map email column
- Create audience
Automated Sync (Advanced)
Use HubSpot API and Facebook Marketing API:
const hubspot = require('@hubspot/api-client');
const bizSdk = require('facebook-nodejs-business-sdk');
// Fetch contacts from HubSpot list
async function syncHubSpotListToFacebook(listId, audienceId) {
const hubspotClient = new hubspot.Client({ accessToken: HUBSPOT_TOKEN });
const contactsResponse = await hubspotClient.crm.lists.listContacts(listId);
const emails = contactsResponse.results.map(contact => contact.properties.email);
// Upload to Facebook Custom Audience
const CustomAudience = bizSdk.CustomAudience;
const audience = new CustomAudience(audienceId);
await audience.addUsers(
['EMAIL'],
[emails]
);
console.log(`Synced ${emails.length} contacts to Facebook audience`);
}
Landing Page Tracking
Track Landing Page Performance
{% if content.template_type == "landing_page" %}
<script>
fbq('track', 'ViewContent', {
content_name: '{{ content.name }}',
content_category: 'landing_page',
content_ids: ['{{ content.id }}']
});
</script>
{% endif %}
Track CTA Clicks
<script>
// Track CTA button clicks
document.querySelectorAll('.hs-cta-wrapper a').forEach(function(cta) {
cta.addEventListener('click', function() {
fbq('trackCustom', 'CTAClick', {
cta_id: this.getAttribute('data-hs-cta-id'),
cta_text: this.innerText
});
});
});
</script>
E-commerce Tracking (HubSpot Commerce Hub)
AddToCart Event
<script>
// Track add to cart actions
document.addEventListener('cart_item_added', function(event) {
fbq('track', 'AddToCart', {
content_ids: [event.detail.sku],
content_name: event.detail.name,
value: event.detail.price,
currency: 'USD'
});
});
</script>
InitiateCheckout Event
<script>
{% if content.template_type == "checkout" %}
fbq('track', 'InitiateCheckout', {
content_ids: [{% for item in cart.items %}'{{ item.sku }}'{% if not loop.last %},{% endif %}{% endfor %}],
num_items: {{ cart.items|length }},
value: {{ cart.total }},
currency: 'USD'
});
{% endif %}
</script>
Troubleshooting
Pixel Not Firing
Check Tracking Code Settings:
- Go to Settings > Tracking & Analytics > Tracking Code
- Verify pixel code is in Footer HTML
- Check for JavaScript errors in console
Verify Page Type:
// Check HubSpot page type
console.log('{{ content.template_type }}');
Test Pixel Loading:
// In browser console
console.log(typeof fbq);
// Should output: "function"
Events Not Recording
Check Form Events:
// Monitor all HubSpot form events
window.addEventListener('message', function(event) {
console.log('HubSpot event:', event.data);
});
Enable Debug Mode:
fbq('init', 'YOUR_PIXEL_ID', {}, {
debug: true
});
Common Error Messages
"fbq is not defined"
- Pixel code not loaded properly
- Check for ad blockers
- Verify code is in Footer HTML, not Header
Forms Not Tracking
- Ensure form submission listener is active
- Check for JavaScript errors
- Verify form is HubSpot form (not custom HTML)
Advanced Matching Issues
- Hash values client-side
- Don't send PII unhashed
- Verify contact properties exist
Privacy and Compliance
GDPR Compliance with HubSpot
HubSpot has built-in privacy features. Integrate consent:
<script>
// Check HubSpot cookie consent
if (window._hsq && window._hsq.push) {
window._hsq.push(['addPrivacyConsentListener', function(consent) {
if (consent.allowed) {
// Load Meta Pixel
!function(f,b,e,v,n,t,s){...}
}
}]);
}
</script>
HubSpot Privacy Policy Integration
Link to your privacy policy:
- Settings > Privacy & Consent
- Enable cookie banner
- Configure tracking consent options
Data Processing Options
For CCPA compliance:
fbq('dataProcessingOptions', ['LDU'], 1, 1000);
Performance Optimization
Lazy Load After HubSpot Scripts
<script>
// Wait for HubSpot to load first
document.addEventListener('DOMContentLoaded', function() {
setTimeout(function() {
// Load Meta Pixel
!function(f,b,e,v,n,t,s){...}
}, 1000);
});
</script>
Conditional Loading by Page Type
{% if content.template_type in ["landing_page", "blog_post"] %}
<!-- Only load pixel on landing pages and blog posts -->
<script>
!function(f,b,e,v,n,t,s){...}
</script>
{% endif %}
Testing and Validation
Meta Pixel Helper
Install Meta Pixel Helper.
Testing Checklist:
- Visit homepage - verify PageView
- View blog post - verify ViewContent
- Submit form - verify Lead event
- Check for errors or warnings
Test Events Tool
In Facebook Events Manager:
- Navigate to Test Events
- Enter your HubSpot domain
- Browse site and submit forms
- Verify events appear in real-time
HubSpot Analytics Validation
Cross-reference with HubSpot:
- Compare form submissions in HubSpot vs Facebook
- Check contact attribution sources
- Verify conversion numbers match
Best Practices
- Use Tracking Code Settings - Easiest to manage across all pages
- Track Forms as Leads - Primary conversion for most HubSpot sites
- Implement CAPI - More reliable for workflow-based conversions
- Sync CRM Lists - Create precise custom audiences
- Monitor Event Match Quality - Aim for 5.0+ score
- Use Advanced Matching - Leverage HubSpot contact data
- Test Thoroughly - Verify all events before launching campaigns
- Respect Privacy - Implement proper consent management
Common Use Cases
Lead Generation Campaign Optimization
- Track form submissions as Lead events
- Create Custom Audience of form submitters
- Build Lookalike Audience
- Optimize ads for Lead conversions
Retargeting Blog Readers
- Track blog post views
- Create audience of specific topic readers
- Retarget with related content offers
- Track form conversions from retargeting
Marketing Qualified Lead (MQL) Campaigns
- Track MQL lifecycle stage changes
- Create audience of MQLs
- Build lookalikes
- Optimize for high-quality leads