i remember seeing docs showing how to generate you...
# ask-questions
i
i remember seeing docs showing how to generate your own uuid to assign to an experiment id (
growthbook.setAttributes({ id: uuid })
). can someone help me find this page?
f
Hi David
ya, one sec
Copy code
const getUUID = () => {
  const COOKIE_NAME = "gbuuid";
  const COOKIE_DAYS = 400; // 400 days is the max cookie duration for chrome

  // use the browsers crypto.randomUUID if set
  const genUUID = () => {
    if(window?.crypto?.randomUUID) return window.crypto.randomUUID();
    return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
      (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
    );
  }
  const getCookie = (name) => {
    let value = `; ${document.cookie}`;
    let parts = value.split(`; ${name}=`);
    if (parts.length === 2) return parts.pop().split(';').shift();
  }
  const setCookie = (name, value) => {
    var d = new Date();
    d.setTime(d.getTime() + 24*60*60*1000*COOKIE_DAYS);
    document.cookie = name + "=" + value + ";path=/;expires=" + d.toGMTString();
  }

  // get the existing UUID from cookie if set, otherwise create one and store it in the cookie
  if(getCookie(COOKIE_NAME)) return getCookie(COOKIE_NAME);
  
  const uuid = genUUID();
  setCookie(COOKIE_NAME, uuid);
  return uuid;
}
Copy code
// minified version:
const getUUID=()=>{let $="gbuuid",e=()=>window.crypto.randomUUID?window.crypto.randomUUID():"10000000-1000-4000-8000-100000000000".replace(/[018]/g,$=>($^crypto.getRandomValues(new Uint8Array(1))[0]&15>>$/4).toString(16)),t=$=>{let e=`; ${document.cookie}`.split(`; ${$}=`);if(2===e.length)return e.pop().split(";").shift()},r=($,e)=>{var t=new Date;t.setTime(t.getTime()+3456e7),document.cookie=$+"="+e+";path=/;expires="+t.toGMTString()};if(t($))return t($);let i=e();return r($,i),i};
i
hi graham, thanks. i’m seeing this typescript issue. can you explain this part of the code?
hi, pinging again
f
Hi David,
[1e7]+-1e3+-4e3+-8e3+-1e11
produces the string
10000000-1000-4000-8000-100000000000
quickly, but typescript doesn't know this is supposed to make a string (it seems). So we can trick it for Typescript with:
Copy code
return (''+[1e7]+-1e3+-4e3+-8e3+-1e11).replace(....