Sticky.ID can be used inside the context of a service worker by utilizing the fetch function. Since we leverage CORS and cookies, it is important to:

  1. Include the service worker origin in the request URL
encodeURIComponent(location.protocol+'//'+location.host)
  1. Send user credentials
credentials: 'include'
  1. Follow redirects (check for cookie support)
redirect: 'follow'

Get the user's Sticky ID using fetch

fetch('https://stickyid-a.akamaihd.net/id?o='+encodeURIComponent(location.protocol+'//'+location.host), {
  credentials: 'include',
  redirect: 'follow'
}).then(function(response) {
  response.json().then(function(json) {
    var globalUserId = json.id;
    var timestamp = json.ts;
    var cookieSupport = json.cs;
  });
});
{"id":"f625e67d9285ac05a110301e4f0a6af7a02ab92f7","ts":1555961788,"cs":1}

Use Sticky ID when handling a push event

A common use case is responding to push events, running an auction, and showing the user a notification with the ad response from the auction. The basic workflow is simple when handling the push event:

  1. Fetch the user's Sticky.ID
  2. Include the user ID on the request to an ad server
  3. Show a notification with the contents of the ad response
/*
 * Push event handler.
 */
self.addEventListener('push', function(event) {
  var promise = fetchStickyID()
    .then(requestAd)
    .then(showNotification);
  
  event.waitUntil(promise);
});

/*
 * Fetches the user's Sticky.ID
 */
function fetchStickyID() {
  return fetch('https://stickyid-a.akamaihd.net/id?o='+encodeURIComponent(location.protocol+'//'+location.host), {
    credentials: 'include',
    redirect: 'follow'
  }).then(function(response) {
    return response.json();
  });
}

/*
 * Sends auction request to ad server and responds with JSON payload.
 */
function requestAd(stickyIDInfo) {
  return fetch('https://ad-server/request-ad?stickyid='+encodeURIComponent(stickyIDInfo.id))
    .then(function(response) {
      return response.json();
    });
}

/*
 * Shows browser notification using details from the ad response payload.
 */
function showNotification(adResponse) {
  return self.registration.showNotification(adResponse.title, adResponse);
}