X Ads Setup & Implementation | OpsBlu Docs

X Ads Setup & Implementation

How to implement X Ads (Twitter) tracking with the X Pixel and Conversions API. Covers pixel installation, conversion event setup, tailored audience.

X Ads (formerly Twitter Ads) uses the X Pixel and Conversions API to track website actions driven by promoted posts, video ads, and follower campaigns on the X platform. The X Pixel provides client-side event capture, while the Conversions API offers server-side redundancy. Without both systems working correctly, X's campaign optimization runs on incomplete data -- the platform cannot learn which audiences, keywords, or ad placements drive actual business outcomes, leading to inefficient spend allocation.

Why Proper Implementation Matters

Real-Time Conversation Targeting

X's unique advertising value lies in real-time conversation targeting:

  • Keyword targeting: Ads appear to users who recently posted about specific topics
  • Follower lookalikes: Target users similar to followers of specific accounts
  • Event targeting: Align ads with trending topics, live events, and cultural moments
  • Conversation targeting: Reach users engaging with specific conversation categories

Conversion data feeds back into these targeting signals. When the pixel attributes purchases to users who tweeted about a specific topic, X's algorithm learns which conversations predict buying behavior.

What Breaks Without Tracking

  • Optimized bidding (Target CPA, Maximum Bid) lacks conversion signal for bid adjustment
  • Website traffic campaigns cannot measure cost per site visit or cost per action
  • Tailored Audiences from website visitors cannot populate for retargeting
  • Conversion attribution is missing, making X appear less effective than it actually is
  • Event-based targeting cannot be evaluated for ROI without conversion data

Platform-Specific Challenges

X Ads measurement faces unique challenges:

  • Ad blocker prevalence: X's tech-savvy user base has higher ad blocker adoption (35-45% on desktop)
  • Platform volatility: X's advertising platform has undergone significant changes since 2022; pixel implementation should be validated regularly
  • Verification requirements: X may require business verification for full ad features
  • API changes: The Conversions API endpoint and authentication have evolved; use the latest documentation

Pre-Implementation Planning

Access and Permissions

X Ads Account:

  1. Log in at ads.x.com (or ads.twitter.com which redirects)
  2. Set up an Ads account if not already active
  3. Add payment method and verify billing
  4. For agencies: Request access as an ad account collaborator

Required Access:

Platform Role Purpose
X Ads Manager Account Administrator Pixel creation, conversion setup
X Developer Portal App Developer API tokens for Conversions API
Google Tag Manager Publish Deploy X Pixel tags
Server environment Deploy Conversions API endpoint

Key Identifiers:

  • Pixel ID: Found in X Ads Manager > Tools > Events Manager > Pixel ID (format: alphanumeric)
  • Ad Account ID: In Ads Manager > Account Settings
  • API Key and Secret: Generated in X Developer Portal for Conversions API
  • Bearer Token: OAuth 2.0 token for API authentication

Conversion Event Planning

X supports these standard event types:

Event Use Case Key Parameters
Page View All page visits None required (fires automatically with base pixel)
Purchase E-commerce transactions value, currency, num_items, order_id
Sign Up Account registrations value, currency
Lead Form submissions value, currency
Add to Cart Cart additions value, currency, num_items
Content View Product/content pages content_type, content_id
Search Site search search_string
Start Checkout Checkout initiation value, currency, num_items
Add Payment Info Payment method entry value, currency
Download App or content download None
Custom Any other event Custom parameters

Attribution Windows

Configure in Ads Manager > Tools > Events Manager:

Type Options Default
Post-engagement (click) 1, 7, 14, 30 days 30 days
Post-view (impression) 1, 7, 14, 30 days 1 day
Post-engagement attribution First or last touch Last touch

Implementation Walkthrough

Step 1: Create X Pixel in Ads Manager

  1. Go to X Ads Manager at ads.x.com
  2. Navigate to Tools > Events Manager
  3. Click Add Event Source > Install with a Pixel
  4. X generates a Pixel ID and base code
  5. Copy the Pixel ID for deployment

Step 2: Deploy X Pixel Base Code

The base pixel goes on every page to track site visits and enable audience building.

Direct Installation:

<!-- X Pixel Base Code -->
<script>
  !function(e,t,n,s,u,a){e.twq||(s=e.twq=function(){s.exe?s.exe.apply(s,arguments):s.queue.push(arguments);
  },s.version='1.1',s.queue=[],u=t.createElement(n),u.async=!0,u.src='https://static.ads-twitter.com/uwt.js',
  a=t.getElementsByTagName(n)[0],a.parentNode.insertBefore(u,a))}(window,document,'script');
  twq('config','YOUR_PIXEL_ID');
</script>
<!-- End X Pixel Base Code -->

Via Google Tag Manager:

  1. Create a new Custom HTML tag
  2. Paste the X Pixel code
  3. Replace YOUR_PIXEL_ID with your actual Pixel ID
  4. Set trigger: All Pages
  5. For consent management: Add a consent condition for ad_storage

The base code automatically fires a Page View event on every page load.

Step 3: Implement Conversion Events

Purchase Event:

// On order confirmation page
twq('event', 'tw-YOUR_PIXEL_ID-purchase', {
  value: 129.98,
  currency: 'USD',
  num_items: 2,
  order_id: 'ORD-2024-12345',
  contents: [
    { content_id: 'SKU-12345', content_name: 'Premium Widget', num_items: 1, content_price: 49.99 },
    { content_id: 'SKU-67890', content_name: 'Deluxe Gadget', num_items: 1, content_price: 79.99 }
  ]
});

Lead Generation Event:

// On form submission success
twq('event', 'tw-YOUR_PIXEL_ID-lead', {
  value: 50.00,
  currency: 'USD',
  conversion_id: 'LEAD-2024-67890'
});

Sign Up Event:

// On account creation success
twq('event', 'tw-YOUR_PIXEL_ID-signup', {
  value: 0,
  currency: 'USD'
});

Add to Cart Event:

// On add-to-cart action
twq('event', 'tw-YOUR_PIXEL_ID-addtocart', {
  value: 49.99,
  currency: 'USD',
  num_items: 1,
  contents: [
    { content_id: 'SKU-12345', content_name: 'Premium Widget', num_items: 1, content_price: 49.99 }
  ]
});

Content View Event:

// On product or content pages
twq('event', 'tw-YOUR_PIXEL_ID-viewcontent', {
  content_type: 'product',
  content_id: 'SKU-12345',
  content_name: 'Premium Widget',
  value: 49.99,
  currency: 'USD'
});

Step 4: GTM Data Layer Integration

// Push purchase data to data layer on order confirmation
dataLayer.push({
  'event': 'x_purchase',
  'transactionId': 'ORD-2024-12345',
  'transactionRevenue': 129.98,
  'transactionCurrency': 'USD',
  'itemCount': 2,
  'items': [
    { id: 'SKU-12345', name: 'Premium Widget', price: 49.99, quantity: 1 },
    { id: 'SKU-67890', name: 'Deluxe Gadget', price: 79.99, quantity: 1 }
  ]
});

GTM Custom HTML Tag:

<script>
  twq('event', 'tw-YOUR_PIXEL_ID-purchase', {
    value: {{DLV - Transaction Revenue}},
    currency: '{{DLV - Transaction Currency}}',
    num_items: {{DLV - Item Count}},
    order_id: '{{DLV - Transaction ID}}'
  });
</script>

Trigger: Custom Event where Event Name equals x_purchase.

Step 5: Implement Conversions API

Server-side tracking bypasses ad blockers and provides more reliable conversion data.

const crypto = require('crypto');
const OAuth = require('oauth-1.0a');

const X_ADS_API_URL = 'https://ads-api.x.com/12/measurement/conversions';
const PIXEL_ID = 'YOUR_PIXEL_ID';

// OAuth 1.0a credentials (from X Developer Portal)
const oauth = OAuth({
  consumer: {
    key: 'YOUR_API_KEY',
    secret: 'YOUR_API_SECRET'
  },
  signature_method: 'HMAC-SHA1',
  hash_function(base_string, key) {
    return crypto.createHmac('sha1', key).update(base_string).digest('base64');
  }
});

const token = {
  key: 'YOUR_ACCESS_TOKEN',
  secret: 'YOUR_ACCESS_TOKEN_SECRET'
};

function hashData(value) {
  if (!value) return null;
  return crypto.createHash('sha256')
    .update(value.toLowerCase().trim())
    .digest('hex');
}

async function sendConversion(eventData) {
  const payload = {
    conversions: [{
      conversion_time: new Date().toISOString(),
      event_id: eventData.event_id,
      identifiers: [{
        twclid: eventData.twclid,       // X click ID from URL parameter
        hashed_email: hashData(eventData.email),
        hashed_phone_number: hashData(eventData.phone)
      }],
      conversion_id: eventData.order_id,
      contents: eventData.items?.map(item => ({
        content_id: item.id,
        content_name: item.name,
        content_price: item.price,
        num_items: item.quantity,
        content_type: 'product'
      })),
      value: eventData.value,
      number_items: eventData.item_count,
      price_currency: eventData.currency || 'USD'
    }]
  };

  const requestData = {
    url: X_ADS_API_URL + `/${PIXEL_ID}`,
    method: 'POST'
  };

  const headers = oauth.toHeader(oauth.authorize(requestData, token));
  headers['Content-Type'] = 'application/json';

  const response = await fetch(requestData.url, {
    method: 'POST',
    headers: headers,
    body: JSON.stringify(payload)
  });

  return response.json();
}

// Example: Send purchase from order handler
await sendConversion({
  event_id: 'purchase_ORD-2024-12345',
  twclid: req.query.twclid || req.cookies._twclid,  // Capture from URL or cookie
  email: 'customer@example.com',
  phone: '+15551234567',
  order_id: 'ORD-2024-12345',
  value: 129.98,
  currency: 'USD',
  item_count: 2,
  items: [
    { id: 'SKU-12345', name: 'Premium Widget', price: 49.99, quantity: 1 },
    { id: 'SKU-67890', name: 'Deluxe Gadget', price: 79.99, quantity: 1 }
  ]
});

Important: Capture the twclid parameter from the landing page URL when users click X ads. Store it in a cookie or session for later use when they convert.

// Capture twclid from URL on landing page
const urlParams = new URLSearchParams(window.location.search);
const twclid = urlParams.get('twclid');
if (twclid) {
  document.cookie = `_twclid=${twclid}; max-age=${30 * 24 * 60 * 60}; path=/; secure; samesite=lax`;
}

Step 6: Build Tailored Audiences

  1. In X Ads Manager, navigate to Tools > Audiences
  2. Click Create Audience

Website Activity Audience:

  • Source: Website tag
  • Event: Select pixel event (Page View, Purchase, etc.)
  • Lookback window: 7, 14, 30, 60, or 90 days
  • URL filters: Include or exclude specific URLs

Recommended Audiences:

Audience Event Window Use
All Visitors Page View 30 days Broad retargeting
Product Viewers Content View 14 days Mid-funnel retargeting
Cart Abandoners Add to Cart minus Purchase 7 days High-intent retargeting
Recent Purchasers Purchase 30 days Suppression or cross-sell
Engaged Visitors Multiple page views 14 days Quality traffic retargeting

Tailored Audience from Lists:

  • Upload hashed email or Twitter handle lists
  • Minimum 100 matches for targeting
  • Use for CRM-based targeting and lookalike expansion

Lookalike Audiences:

  • Based on any Tailored Audience with sufficient size
  • Expand reach to users with similar characteristics
  • Set similarity level: Narrow (more similar) vs. Broad (larger reach)

Verification and QA

X Pixel Helper

Install the X Pixel Helper Chrome extension:

  1. Navigate through your conversion funnel
  2. Click the extension icon
  3. Verify:
    • Pixel ID matches your account
    • Page View event fires on every page
    • Conversion events fire correctly with parameters
    • No errors or warnings

Events Manager

  1. In X Ads Manager, go to Tools > Events Manager
  2. Check Event Activity tab
  3. Verify:
    • Events appear within minutes of firing
    • Event counts match test conversions
    • Parameter values (value, currency, order_id) are correct

Network Tab Debugging

  1. Open Chrome DevTools > Network tab
  2. Filter for ads-twitter.com or static.ads-twitter.com
  3. Complete a conversion
  4. Verify:
    • Pixel request fires with correct event type
    • Parameters are populated in the request payload
    • Response status is 200

Conversions API Validation

  1. Send test conversions via the API
  2. Check Events Manager for server-side event delivery
  3. Verify deduplication between pixel and API events (use matching event_id)

Common Issues

Issue Cause Fix
Pixel not firing Ad blocker or script error Test in incognito, check console for errors
No events in Events Manager Wrong Pixel ID Verify ID in pixel code matches Ads Manager
Revenue shows $0 Value parameter missing Check data layer variable, ensure numeric type
Audiences not populating Pixel active but no URL match Review audience URL filters and event conditions
twclid not captured URL parameter stripped by redirect Capture twclid before any redirects
API auth failing Invalid OAuth credentials Regenerate tokens in Developer Portal

Deployment Artifacts

  • Pixel ID: Central reference for all tag deployments
  • API credentials: OAuth keys, tokens, and secrets (store securely)
  • Tracking plan: Events, parameters, and trigger conditions
  • GTM container documentation: Tags, triggers, variables, and version history
  • Audience definitions: Names, event sources, windows, and URL filters
  • twclid capture implementation: Landing page script and cookie storage
  • Attribution windows: Click and view windows with rationale
  • Environment matrix: Pixel IDs and API credentials per environment

Linked Runbooks

Change Log and Owners

  • Document who manages the X Ads account and Developer Portal credentials
  • Track pixel event additions and modifications with dates
  • Record audience definition changes and membership durations
  • Maintain API credential rotation schedule
  • Review monthly: pixel health, conversion volumes, audience sizes, API delivery success