SDK for JavaScript Reference Guide
Use this SDK to facilitate the process of establishing client identity using EUID and retrieving advertising tokens. The following sections describe the high-level workflow for establishing EUID identity, provide the SDK API reference, and explain the EUID storage format.
If you're using Prebid.js with the EUID Identity Module, or with another product that has EUID support, you probably don't need to use the SDK at all. The Prebid.js module manages everything. For details, see EUID Client-Side Integration Guide for Prebid.js.
This page describes version 3 of the SDK for JavaScript. If you are maintaining an integration using an earlier version, do one of the following:
- Upgrade your integration, using the migration guide (recommended).
- Refer to the documentation for earlier versions of the SDK.
Related information:
For integration steps for content publishers, see:
For example applications with associated documentation, see:
- The EUID Google Secure Signals with SDK v3 example:
- Code and docs
- Running site: Client-Side EUID SDK Integration Example.
Functionality
This SDK simplifies development for publishers who want to build their own customized EUID integration. The following table shows the functions it supports.
Encrypt Raw EUID to EUID Token | Decrypt EUID Token to Raw EUID | Generate EUID Token from Personal Data | Refresh EUID Token | Map Personal Data to a Raw EUID |
---|---|---|---|---|
— | — | ✅ | ✅ | — |
API Permissions
To use this SDK, you'll need to complete the EUID account setup by following the steps described in the Account Setup page.
You'll be granted permission to use specific functions offered by the SDK, and given credentials for that access. Bear in mind that there might be functions in the SDK that you don't have permission to use. For example, publishers get a specific API permission to generate and refresh tokens, but the SDK might support other activities that require a different API permission.
For details, see API Permissions.
SDK Version
This documentation is for version 3 of the SDK for JavaScript.
GitHub Repository
The source for this SDK is in the following open-source GitHub repository:
SDK Distribution
The SDK is published in these locations:
-
CDN:
https://cdn.prod.uidapi.com/uid2-sdk-${VERSION_ID}.js
As of the latest update to this document, the most recent version is 3.4.5. You can also see the list of available versions.
-
CDN (Integration):
https://cdn.integ.uidapi.com/uid2-sdk-${VERSION_ID}.js
This integration URL contains un-minified code and is intended for testing purposes only. Do not use this URL for your production site.
As of the latest update to this document, the most recent version is 3.4.5. You can also see the list of available versions.
Terminology
In this document, the following terms apply:
- Identity refers to a package of values, returned by the POST /token/generate or POST /token/refresh endpoint, that includes the EUID token, the refresh token, and associated values such as timestamps.
- Advertising token refers to the EUID token.
- Callback function refers to a callback function built for the current version of this SDK and registered using the Array Push Pattern.
- Legacy callback function refers to a callback function built for version 1.x or 2.x of this SDK and registered in the call to
init
.
Include the SDK Script
On every page where you want to use EUID for targeted advertising, include the following SDK script:
<script src="https://cdn.prod.uidapi.com/uid2-sdk-3.4.5.js" type="text/javascript"></script>
Async or Defer Loading the SDK Script
Version 3 and above of the SDK can be used with async
or defer
script loading.
If you are using async
or defer
script loading on your site, do the following:
-
(Required) Make sure you are calling
__euid.init
from a callback function when it receives theSdkLoaded
event. -
(Required) Add the relevant attribute to the script tag.
-
(Recommended) Make sure that the script tag is in the
<head>
portion of the page, as shown in the following example:<head>
<!-- ... -->
<script async src="https://cdn.prod.uidapi.com/uid2-sdk-3.4.5.js" type="text/javascript"></script>
<!-- ... -->
</head>
Workflow Overview
The high-level client-side workflow for establishing EUID identity using the SDK consists of the following steps:
-
Register a callback function using the Array Push Pattern.
-
When your callback receives the
SdkLoaded
event, initialize the SDK using the init function. -
Wait for your event listener to receive the
InitCompleted
event. The event data indicates the identity availability:- If the identity is available, it is returned in the event payload. The SDK sets up a background token auto-refresh.
- If the identity is unavailable, the
identity
property on the payload is null. No EUID is available until you provide an identity to the SDK.
-
Handle the
IdentityUpdated
callback event that indicates changes to the identity.The
identity
property on the event payload either contains the new identity, or is null if a valid identity is not available. -
Handle the identity based on its state:
- If the advertising token is available, use it to initiate requests for targeted advertising.
- If the advertising token is not available, either use untargeted advertising or redirect the user to the data capture with the consent form.
For more detailed web integration steps, see Client-Side Integration Guide for JavaScript.
Background Token Auto-Refresh
As part of the SDK initialization, a token auto-refresh for the identity is set up, which is triggered in the background by the timestamps on the identity or by failed refresh attempts due to intermittent errors.
Here's what you need to know about the token auto-refresh:
- Only one token refresh call can be active at a time.
- If the POST /token/refresh response is unsuccessful because the user has opted out, or because the refresh token has expired, this suspends the background auto-refresh process. To use EUID-based targeted advertising again, you must obtain the email from the consumer. In all other cases, auto-refresh attempts continue in the background.
- All callback functions provided using the Array Push Pattern are invoked in the following cases:
- After each successful refresh attempt.
- When identity has become invalid—for example, because the user has opted out.
NOTE: The callback is not invoked when identity is temporarily unavailable and the auto-refresh keeps failing. In this case, the SDK continues using the existing advertising token as long as it hasn't expired.
- A disconnect() call cancels the active timer.
Callback Function
You can register functions to receive events from the EUID SDK using the Array Push Pattern. There are a number of events currently available:
SdkLoaded
is raised after the SDK has been parsed and the global__euid
object has been constructed. This is useful for callinginit()
, especially if your script loading order is not guaranteed (for example, if you are usingasync
ordefer
script loading).InitCompleted
is raised wheninit()
has finished and the SDK is ready for use. If an identity was provided in theinit
call, or the SDK was able to load a previously-provided identity, the identity is included in the payload.IdentityUpdated
is raised whenever there is a new identity available, or the existing identity is no longer available.
You can provide as many callback functions as you want, and register them from anywhere. This allows you to split your code up in a way that makes sense for your site.
Callback Function Signature
Your callback function should accept two parameters: an event type and a payload. The type of the payload depends on the event type.
The following example callback handles the SdkLoaded
event to call init and then, if an identity isn't available once init
has completed, uses the InitCompleted
event to provide an identity.
- JavaScript
- TypeScript
window.__euid = window.__euid || {};
window.__euid.callbacks = window.__euid.callbacks || [];
window.__euid.callbacks.push((eventType, payload) => {
if (eventType === 'SdkLoaded') {
__euid.init({});
}
if (eventType === 'InitCompleted' && !payload.identity) {
const generatedIdentity = await requestIdentityFromServer(); // Call your server-side integration to generate a token for the logged-in user
__euid.setIdentity(generatedIdentity);
}
});
import { EventType, CallbackPayload } from "./callbackManager";
window.__euid = window.__euid || {};
window.__euid.callbacks = window.__euid.callbacks || [];
window.__euid.callbacks.push((eventType: EventType, payload: CallbackPayload) => {
if (eventType === 'SdkLoaded') {
__euid.init({});
}
if (eventType === 'InitCompleted' && !payload.identity) {
const generatedIdentity = await requestIdentityFromServer(); // Call your server-side integration to generate a token for the logged-in user
__euid.setIdentity(generatedIdentity);
}
});
Event Types and Payload Details
Event | Payload | Details |
---|---|---|
SdkLoaded | {} | Called when the SDK script has loaded and the global __euid has been constructed. When you receive this event, it is safe to call __euid.init . Callbacks always receive this event once. If the SDK has already been loaded when the callback is registered, it receives the event immediately. |
InitCompleted | { identity: Identity | null } | Called once init() has finished. Callbacks always receive this event once, as long as a successful call to init has been made. If init has already been completed when the callback is registered, it receives this immediately after it receives the SdkLoaded event. |
IdentityUpdated | { identity: Identity | null } | Called whenever the current identity changes. If the identity doesn't change after the callback is registered, callbacks do not receive this event. |
The Identity
type is the same type as the identity you can provide when calling init()
.
Array Push Pattern
In order to best support script tags that are not guaranteed to load in order (for example, if you're using async
or defer
script tags), use the following pattern to register callbacks:
window.__euid = window.__euid || {};
window.__euid.callbacks = window.__euid.callbacks || [];
window.__euid.callbacks.push(callbackFunction);
This ensures the following:
- If your code runs before the SDK has loaded (meaning the global
__euid
object is not available), you can still provide a callback that the SDK can find. - If the SDK runs before your code does, you do not overwrite the
__euid
object or thecallbacks
array. - If multiple callbacks are registered using this pattern, they do not overwrite each other.
Provide an Identity to the SDK
Unless the SDK is able to load a previously-stored identity from local storage or the cookie, you must provide an identity to it. There are several ways to do this:
- Provide an Identity by Setting a First-Party Cookie
- Provide an Identity in the Call to
init
- Provide an Identity by Calling
setIdentity
Provide an Identity by Setting a First-Party Cookie
If you store a first-party cookie, as described in the storage format section, and the value is newer than the value available in local storage, the SDK loads the value from the cookie. If you have set the useCookie
init option to true
, it always loads this value, and does not check local storage. You can control several other things about the cookie using init parameters.
Provide an Identity in the Call to init
You can provide a new identity when you call init
.
Provide an Identity by Calling setIdentity
At any time after init
has completed, you can call setIdentity
to provide the SDK with a new identity to use.
API Reference
All interactions with the SDK for JavaScript are done through the global __euid
object, which is an instance of the EUID
class. All of the following JavaScript functions are members of the EUID
class:
- constructor()
- init()
- getAdvertisingToken()
- getAdvertisingTokenAsync()
- isLoginRequired()
- disconnect()
- abort()
- callbacks NEW IN V3
- setIdentity() NEW IN V3
- getIdentity() NEW IN V3
- isInitComplete() NEW IN V3
constructor()
Constructs an EUID object. This is not intended to be used directly: when the SDK loads, it automatically initializes an instance of the EUID class and stores it as the global __euid object. Advanced integrations may make use of this constructor directly, but must take care to avoid having multiple active instances of the SDK running. This is not a supported use case.
Instead of calling this function, just use the global __euid
object.
init(opts: object): void
Initializes the SDK and establishes user identity for targeted advertising.
Here's what you need to know about this function:
- You can call
init()
any time after the SDK has been loaded. The recommended way to do this is by registering a callback function that handles theSdkLoaded
event using the Array Push Pattern. By using this pattern you can make sure that your code works regardless of script load order, and that usingasync
ordefer
on your script tags does not cause EUID SDK errors. - The
identity
property in theinit()
call refers to thebody
property of the response JSON object returned from a successful POST /token/generate or POST /token/refresh call with the server-side generated identity. This is a good way to provide the identity if your server-side integration ensures you always have a current token available and it is more convenient to provide it using JavaScript. - If the
identity
property in theinit()
call is falsy, the SDK attempts to load the identity from local storage or the cookie.- Once
init()
is complete, all callbacks receive theInitCompleted
event. If theidentity
property on the payload of this event is null, no identity could be loaded, and you should therefore provide an identity to the SDK. This is the recommended way to provide an identity if your server-side integration does not ensure a current identity is always available, and you need to request it from the server only when necessary. - If you are using a first-party cookie (see EUID Storage Format) to store the passed EUID information for the session, a call to
init()
made by a page on a different domain might not be able to access the cookie. You can adjust the settings used for the cookie with thecookieDomain
andcookiePath
options.
- Once
- To tune specific behaviors, initialization calls might include optional configuration init parameters.
The following is an example of an init()
call made using a callback with the server-side generated identity included.
<script>
window.__euid = window.__euid || {};
window.__euid.callbacks = window.__euid.callbacks || [];
window.__euid.callbacks.push((eventType, payload) => {
if (eventType === "SdkLoaded") {
__euid.init({
identity : { // The `body` property value from the token/generate or token/refresh API response.
"advertising_token": "E4AAAABl85Pd1yKbznQL58Q_09bAJtGbGl2e-JCLPLGUSsz7ao6iR11QySi-kLtJ7suJAn3lK474gJvOLVK0_BZe8FABStV44hHWoFt9IfWVj35PIWQJ8VoJzrmHhh6YyQDtQ3q_t0ZJL9OjB8cXa94dMDhlGzi3j5K4o9cH3X1OYgJFQDat4L2cj7HMptpWUO9dheldwpVhgfAlLdEw9D3xtA",
"identity_expires": 1724998239163,
"refresh_expires": 1725081039163,
"refresh_from": 1724995539163,
"refresh_response_key": "JZcp6vMDhuMUPAA03QnsW74MhNn4Ng37XRCNChyeX2k=",
"refresh_token": "EAAAAGb41t8MrmTpHpDWYi67K8ok7qo87IQwan5Ghz4CGPz3pYXCoS/bAEygLYa0tjMPw6v1q2UsjQQ7SURA6tq7VvTdROOkxJ6YcNiaCeCpINoZYT5xzsPp9VgkkWT0HkxLYdMUt3M7KMJ+gziJQZGsoMeEYTMR3yEO5w+A7N1uW71Q7PWyTJaRab7F0hUdmwHwN9ZdDj/+Ky/qzf8YBGPzSWvpN7Ry9gT6EQxVZSZIj6PSzFxvSPVt48i59VpJ6zvOL4MKCAtiAFZ92DUeKfGYZ3XptcbO2srOFaAgeJm2hiSOKWPxYfhCBPZa2yYbKRc+UFNO7L+UnxlL+VRU1GTZm3zncDpXlif1lqmfXuza+KMXQmPzuhzxljn0nkUBa8OC"
}
});
}
});
</script>
The following is an example of an init()
call that loads a previously-provided identity from local storage, if one is available. You can put a script like this on any page that the user might visit after the identity has been established.
<script>
window.__euid = window.__euid || {};
window.__euid.callbacks = window.__euid.callbacks || [];
window.__euid.callbacks.push((eventType, payload) => {
if (eventType === "SdkLoaded") {
__euid.init({}); // Note that you must provide a configuration object, even if you're not providing any options.
}
});
</script>
Init Parameters
The opts
object supports the following properties.
Property | Data Type | Attribute | Description | Default Value |
---|---|---|---|---|
identity | object | Optional | The body property value from a successful POST /token/generate or POST /token/refresh call that has been run on the server to generate an identity.To use the identity from a first-party cookie (see EUID Storage Format), leave this property empty. | N/A |
baseUrl | string | Optional | The custom base URL of the EUID operator to use when invoking the POST /token/refresh endpoint. For example: https://my.operator.com . | https://prod.uidapi.com . |
refreshRetryPeriod | number | Optional | The number of milliseconds after which to retry refreshing a token if an intermittent error occurs. This value must be >= 1000. | 5000 |
cookieDomain | string | Optional | The domain name string to apply to the EUID cookie (see EUID Storage Format). For example, if the baseUrl is https://my.operator.com , the cookieDomain value might be operator.com . | undefined |
cookiePath | string | Optional | The path string to apply to the EUID cookie (see EUID Storage Format). | / |
useCookie | boolean | Optional | Set this to true to tell the SDK to store the identity in cookie storage instead of local storage. You can still provide an identity using a first-party cookie if this value is false or not provided. | |
callback | function(object): void | Deprecated | The function that the SDK should invoke after validating the passed identity. Do not use this for new integrations. | N/A |