How to Set Up External ID Tracking for Facebook CAPI with GTM

11 Feb, 2026

If you’re running Facebook Conversions API (CAPI) through Google Tag Manager, you need a way to track users consistently across sessions. This External ID script does exactly that—it creates a unique identifier for each visitor and stores it in a cookie.

What This Does

This JavaScript variable generates a persistent External ID for Facebook’s server-side tracking. It checks for an external_id in the URL first, then looks for an existing cookie, and if neither exists, it creates a new unique ID (UUID) and saves it for future visits.

The External ID Code

function() {
  function generateUUID() {
    var d = new Date().getTime();
    var d2 = (performance && performance.now && (performance.now()*1000)) || 0;
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      var r = Math.random() * 16;
      if(d > 0){
        r = (d + r)%16 | 0;
        d = Math.floor(d/16);
      } else {
        r = (d2 + r)%16 | 0;
        d2 = Math.floor(d2/16);
      }
      return (c==='x' ? r : (r&0x3|0x8)).toString(16);
    });
  }
  
  function setCookie(name, value, days) {
    var expires = "";
    if (days) {
      var date = new Date();
      date.setTime(date.getTime() + (days*24*60*60*1000));
      expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "") + expires + "; path=/";
  }
  
  function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
      var c = ca[i];
      while (c.charAt(0)==' ') c = c.substring(1,c.length);
      if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
  }
  
  var urlParams = new URLSearchParams(window.location.search);
  var externalIdFromUrl = urlParams.get('external_id');
  var externalIdFromCookie = getCookie('external_id');
  
  if (externalIdFromUrl && externalIdFromUrl !== '') {
    setCookie('external_id', externalIdFromUrl, 365);
    return externalIdFromUrl;
  }
  
  if (externalIdFromCookie && externalIdFromCookie !== '') {
    return externalIdFromCookie;
  }
  
  var generatedUUID = generateUUID();
  setCookie('external_id', generatedUUID, 365);
  return generatedUUID;
}
JavaScript

How It Works

The script follows this logic:

  1. Check URL first – If there’s an external_id parameter in the URL (like from an email campaign), it uses that and saves it to a cookie
  2. Check existing cookie – If a cookie already exists from a previous visit, it returns that value
  3. Generate new ID – If neither exists, it creates a fresh UUID and stores it in a cookie for 365 days

This means once a visitor lands on your site, they keep the same External ID across all their sessions for a year.

Setting It Up in GTM

Step 1: Create a Custom JavaScript Variable

In Google Tag Manager:

  • Go to Variables → New
  • Choose Custom JavaScript as the variable type
  • Paste the code above
  • Name it something like “JS – External ID”
  • Save it

Step 2: Use It in Your Facebook CAPI Tag

When setting up your Facebook Conversions API tag (either through a template or custom setup):

  • Find the External ID field
  • Reference your variable: {{JS - External ID}}
  • For server-side variable name, use: x-fb-ud-external_id

Step 3: Test It

Use GTM Preview Mode and check:

  • Does the variable generate a UUID on first visit?
  • Does it persist when you reload the page?
  • Does it update if you add ?external_id=test123 to your URL?

Check your browser’s cookies (Developer Tools → Application → Cookies) to verify the external_id cookie is being set.

Why You Need This

Facebook’s Conversions API works better when you can match events to the same user across multiple sessions. The External ID helps Facebook:

  • Connect your server-side events to browser events
  • Improve attribution accuracy
  • Reduce data loss from iOS 14.5+ and ad blockers
  • Better track the customer journey

Common Use Cases

Email Campaigns: Add ?external_id= to your email links with the user’s hashed email or customer ID. When they click through, this script will save that ID and use it for all tracking.

CRM Integration: Pass your internal customer ID as the external_id parameter when users click from your CRM or customer portal.

Cross-Device Tracking: Since the ID is stored in a cookie, it persists across sessions on the same device/browser.

Privacy Notes

  • This creates a first-party cookie on your domain
  • The UUID is randomly generated and doesn’t contain personal information
  • Make sure your privacy policy covers the use of tracking cookies
  • Consider implementing consent management if required in your region

Troubleshooting

Cookie not persisting? Check if your site has strict cookie policies or if users are blocking cookies.

ID changing on every page? Make sure the variable is set to fire on all pages and that your cookie domain settings are correct.

Not working with CAPI? Verify you’re using the correct server-side variable name format (x-fb-ud-external_id) in your Facebook tag configuration.

That’s it. Once this is set up, you’ll have consistent External ID tracking for your Facebook Conversions API implementation.

Related Posts

Stop Double Conversions from Page Reloads in GTM

When someone refreshes your thank you page, your conversion tags fire again. This inflates your numbers and wastes ad budget. Here's a quick fix. The Problem User submits a form → lands on thank you page → conversion fires ✓ User hits refresh → conversion fires again...

read more

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

Shibbir Ahmed

Hi, I’m here to help you learn Google Tag Manager and Google Analytics. Join thousands of other digital marketers and digital analysts in this exciting journey.
Book Meeting

Search Tags

Claim FREE Audit