Programmatic

UID2 Setup Guide for Prebid.js and Publisher Ad Ops

To set up Unified ID 2.0 (UID2) in Prebid.js, publishers must generate encrypted advertising tokens from normalized, SHA-256 hashed user email addresses and pass them into the Prebid User ID module (`uid2IdSystem`). These tokens are automatically attached to outgoing bid requests within the OpenRTB `eids` array, allowing Demand-Side Platforms (DSPs) to bid accurately on authenticated inventory without relying on third-party cookies.

Key Takeaways

  • CSTG Simplifies Integration: Client-Side Token Generation (CSTG) allows publishers to generate UID2 tokens directly in the browser using a public key, bypassing the need for custom server-side infrastructure.
  • EIDS Payload Standard: Prebid automatically packages verified UID2 tokens into the `user.ext.eids` array with the source identifier `uidapi.com` for programmatic demand partners.
  • Normalization is Required: Raw emails must be stripped of leading/trailing spaces, converted to lowercase, and hashed using SHA-256 prior to token lookup or CSTG calls.
  • Measurable CPM Impact: Targeted DSP buying on identity-resolved traffic routinely commands 20% to 50% higher CPMs compared to unauthenticated, contextual-only bids on cookieless browsers.

How UID2 Functions in Programmatic Monetization

Unified ID 2.0 is an open-source, deterministic identity framework initiated by The Trade Desk and managed by IAB Tech Lab. It replaces third-party cookies by converting authenticated user data—primarily email addresses or phone numbers—into opaque, rotating identity tokens.

When an authenticated user logs into your website, your frontend captures their email address. That email is normalized and converted into a cryptographic SHA-256 hash. The hash is sent to the UID2 Operator Service, which returns an encrypted UID2 Token. Crucially, the raw UID2 (the identifier DSPs use to match audiences) is never exposed directly on the client side. Instead, the browser receives an encrypted token that rotates regularly.

During a header bidding auction, Prebid.js collects this token through its standard User ID Submodule framework. It formats the token into an explicit OpenRTB `eids` (Extended User IDs) object and broadcasts it to every supply-side platform (SSP) adapter configured on your site. Demand-side platforms decrypt the token using private keys managed by the central UID2 administrative framework, matching the user against advertiser first-party target lists without compromising user privacy.

Capturing authenticated identity at the login point relies on clean frontend data collection. If your registration or newsletter flows fail to capture clean inputs, your downstream resolution rates collapse. Implementing sound zero-party data capturing strategies guarantees that your opt-in forms yield normalized data structures from the very first interaction.

Choosing an Architecture: CSTG vs. Server-Side Token Generation

Publishers have two distinct operational paths for converting raw email hashes into UID2 tokens: Client-Side Token Generation (CSTG) or a dedicated Server-Side API integration.

CSTG is the fastest deployment model for standard ad operations teams. It leverages an API Key and a Public Key issued directly inside the Unified ID 2.0 Portal. The browser calls the UID2 Operator endpoint directly to exchange an email hash for an encrypted identity payload. The private API key remains protected because authentication uses asymmetric cryptography via the public key.

Server-side integration requires your backend server to interact directly with the UID2 Operator API or run a private UID2 Operator service in a containerized environment. This model offers tighter security because your backend handles raw user emails and API keys far from the client browser. However, it requires dedicated backend engineering resources and maintenance overhead.

If you already maintain robust infrastructure such as server-side GTM architectures, executing backend identity resolution can streamline security controls across both measurement and monetization tooling.

Feature / Requirement Client-Side Token Generation (CSTG) Server-Side API Integration
Implementation Effort Low (Frontend JS & Prebid.js config only) Medium-High (Backend routes & SDK deployment)
Security Model Public Key cryptographic exchange Private API Key / Secret storage on server
Maintenance Burden Handled automatically by UID2 JS SDK Requires server maintenance & endpoint monitoring
Token Refresh Handling Automated via Prebid / UID2 Integration Code Requires custom backend session or storage refresh logic
Best Used For Standard web publications, fast Ad Ops rollouts Enterprise apps with strict client data boundaries

Step-by-Step Prebid.js UID2 Implementation via CSTG

Setting up UID2 inside Prebid.js requires a specific build sequence and accurate configuration blocks. Follow these five steps to deploy the framework cleanly.

Step 1: Build Prebid.js with the UID2 Submodule

Ensure your Prebid.js binary includes both the standard User ID module (`userId`) and the specific UID2 submodule (`uid2IdSystem`). If you compile Prebid using command-line tools, execute the build process with the explicit module inclusion:

gulp build --modules=userId,uid2IdSystem,appnexusBidAdapter,rubiconBidAdapter

If you download your binary directly from the Prebid.js portal, check the boxes for User ID Core and Unified ID 2.0 in the module selection interface.

Step 2: Obtain Portal Credentials

Log in to the official UID2 Portal managed by your designated administrative entity. Request access credentials for Client-Side Token Generation. You will receive two specific strings required for your web setup:

  • Subscription ID: A UUID string identifying your publisher account within the UID2 system.
  • Public Key: A public cryptographic key used by the browser to encrypt user identity before transmitting it over public networks.

Step 3: Normalize and Hash Customer Emails

Before passing raw user input into the UID2 framework, string normalization is mandatory. Failure to standardize format will generate mismatched SHA-256 signatures, causing identity match rates to drop to zero.

Normalization requires three mandatory transformations:

  1. Remove all leading and trailing whitespace characters.
  2. Convert all characters to lowercase.
  3. For Gmail addresses only, preserve standard text (do not strip dots or plus signs manually unless matching custom internal backend specs; standard UID2 specifications handle standard string formatting directly prior to SHA-256 calculation).

Here is an optimized JavaScript function to normalize and hash an email string using the browser's native `crypto.subtle` API:

async function hashEmail(rawEmail) {
  const normalized = rawEmail.trim().toLowerCase();
  const encoder = new TextEncoder();
  const data = encoder.encode(normalized);
  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('');
}

Step 4: Configure `pbjs.setConfig` for Prebid User ID

Inject the `uid2` module configuration into your existing `pbjs.setConfig` block. When using CSTG, specify your `subscriptionId` and `publicKey`, alongside the hashed email captured from your user login state.

pbjs.que.push(function() {
  pbjs.setConfig({
    userSync: {
      userIds: [{
        name: 'uid2',
        params: {
          subscriptionId: 'YOUR_UID2_SUBSCRIPTION_ID',
          publicKey: 'YOUR_UID2_PUBLIC_KEY',
          emailHash: 'a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3' // Pre-calculated SHA-256
        },
        storage: {
          type: 'html5',
          name: 'uid2_state',
          expires: 30
        }
      }],
      auctionDelay: 500
    }
  });
});

If your backend already generates raw UID2 Token payloads (when using a Server-Side implementation), omit `subscriptionId` and `publicKey` and supply the raw token directly within the `value` param object.

Step 5: Manage Token Refresh and Expiration

UID2 tokens contain internal expiration dates and refresh tokens. The Prebid UID2 submodule handles local storage reads and writes automatically via the `storage` configuration block shown above. It saves the active payload in `localStorage` under key `uid2_state` and continuously evaluates its freshness. If the active advertising token expires during a user session, the submodule uses the internal refresh token to retrieve a fresh token without requiring another email lookup or login event.

Publisher Ad Ops & Google Ad Manager (GAM) Integration

Once Prebid.js compiles and attaches the UID2 payload client-side, the next task belongs to Ad Ops: ensuring supply partners and primary ad servers receive and value these identity-enhanced bid requests.

Prebid Key-Value Mapping vs. OpenRTB Extended IDs

There is a common point of confusion in Publisher Ad Ops regarding whether UID2 requires custom Google Ad Manager (GAM) key-value targeting pairs. The short answer is: not for programmatic SSP execution.

Modern SSP adapters integrated into Prebid.js read identity modules directly from the internal `bidderRequest.userId.uid2` object. They attach this payload into the standard OpenRTB `user.ext.eids` array outbound to their endpoints. GAM line items do not need to target specific `uid2=true` key-values for standard header bidding auctions to benefit from identity enrichment.

However, setting up a dedicated GAM Key-Value (e.g., `has_uid2=true`) can be useful for Ad Ops teams who want to build explicit line items, set conditional floor prices, or report on unified user fill rates directly inside GAM reports. You can populate this targeting dynamically using Prebid callbacks:

pbjs.que.push(function() {
  var userIds = pbjs.getUserIds();
  if (userIds & userIds.uid2) {
    googletag.cmd.push(function() {
      googletag.pubads().setTargeting('has_uid2', 'true');
    });
  } else {
    googletag.cmd.push(function() {
      googletag.pubads().setTargeting('has_uid2', 'false');
    });
  }
});

Configuring SSP Exchange Settings

Even if Prebid passes the UID2 token correctly on the client side, your exchange partners must be configured to pass identity down to buying DSPs. Work directly with your account managers at major supply partners to activate identity processing:

  • Magnite / Rubicon Project: Confirm that user identity passing is enabled in your publisher portal dashboard under Site & Zone settings.
  • PubMatic: Verify that Identity Hub or core Prebid User ID processing is toggled on inside the PubMatic UI.
  • Index Exchange: Ensure your IX wrapper configurations explicitly permit processing of the `uidapi.com` source namespace.
  • OpenX: Check that your publisher account settings permit full identity pass-through for OpenRTB request enrichment.

Testing, Debugging, and Verification

Deploying identity solutions without rigorous QA risks silent failures where bid requests drop tokens without throwing explicit console errors. Perform these verification checks inside Chrome DevTools prior to launching UID2 across production inventory.

Verifying Token Generation via Console

Open your browser developer tools on an authenticated page and execute the following snippet in the console after Prebid loads:

pbjs.getUserIds();

The console will output an object containing active identity modules. Expand the `uid2` property. You should see a structured string or token payload. If `uid2` returns `undefined`, check whether your auction delay (`auctionDelay: 500`) allowed sufficient time for the async token generation call to resolve prior to auction initiation.

Inspecting Outbound OpenRTB Bid Requests

Switch to the Network tab inside Chrome DevTools. Filter requests by your target SSP adapter (for instance, `rubicon`, `appnexus`, or `pubmatic`). Select an outbound auction POST request and view its payload.

Look for the `user.ext.eids` array within the JSON body. A valid UID2 implementation renders a structure matching this exact pattern:

{
  "user": {
    "ext": {
      "eids": [
        {
          "source": "uidapi.com",
          "uids": [
            {
              "id": "AgAAAAC1...[Encrypted Token String]...",
              "atype": 1
            }
          ]
        }
      ]
    }
  }
}

The key string to verify is `"source": "uidapi.com"`. If the source matches `uidapi.com` and the string is populated, your client-side Prebid architecture is operating as intended.

Privacy and Regulatory Alignment

Identity frameworks do not operate independently of privacy laws. UID2 respects user opt-out states globally across participating DSPs and SSPs, but publishers remain responsible for collecting valid consent signals locally before initiating token requests.

When operating under GDPR, the IAB TCF v2.2 framework dictates legal bases for storing and accessing information on a user device (Purpose 1). If a user denies consent for Purpose 1 or Purpose 2, Prebid's User ID module naturally suppresses module execution if consent management modules (CMP) are properly integrated into Prebid.

Verify that your setup aligns with site-wide regulatory configs. Misconfigured consent parameters can block identity lookup calls even when users give valid opt-in responses. Troubleshoot your configuration against established best practices for handling consent signals in ad stacks to avoid dropping bid capabilities during compliance checks.

For US privacy regulations (CCPA/CPRA), UID2 maintains a centralized opt-out portal. When a consumer opts out at `knowyourprivacyrights.org`, the central UID2 Operator revokes the ability for DSPs to decrypt tokens associated with that user's hashed email, invalidating audience matching downstream instantly.

Frequently Asked Questions

What is the difference between UID2 and EUID?

EUID (European Unified ID) is an adaptation of the UID2 framework tailored specifically for the legal and regulatory requirements of the European Union and the UK. While built on similar cryptographic architecture, EUID operates under explicit consent mechanisms aligned with GDPR mandates and relies on distinct Operator endpoints and legal agreements separate from standard North American UID2 deployments.

Does UID2 work without user logins?

No. UID2 is a deterministic identity framework that relies directly on explicit user authentication, such as an email address or phone number captured during registration, login, or newsletter signup. It cannot construct identity tokens from probabilistic signals, IP addresses, or browser fingerprints.

How does UID2 handle user opt-outs?

When a user opts out through the central UID2 privacy portal, their preference is synchronized across all participating operators and DSPs. The UID2 Operator service stops returning valid advertising tokens for that hashed identity, preventing buyers from performing targeted audience matching on subsequent ad requests.

Why is Prebid not sending the UID2 payload in auction requests?

This issue usually stems from three root causes: failing to set an adequate `auctionDelay` (allowing the async API call to complete), invalid SHA-256 email hash formatting (such as unnormalized uppercase letters or unstripped whitespace), or consent management parameters (TCF v2.2/CCPA) actively blocking the User ID submodule execution.