Below is an example of how to generate a cookieless userId for users that have not accepted cookies.
Here, we are overwriting two methods on the default LocalCookieAuthStore (user getter and generateUserId). By doing this, we can generate a cookieless userId if cookies have not been accepted, or use a unique userId if the cookies have been accepted.
If cookies are not accepted, it will create a cookie with a userId that is not unique and will be grouped with other cookieless users. It is overwriting both the generateUserId method and the user getter. This allows for the cookies to be cleared and a new session started if the user cookie acceptance changes.
Below, window.areCookiesAccepted is just an example, but your site's logic should be used in its place.
import XGenClient, { LocalCookieAuthStore, UserRecord } from '@xgenai/sdk-core';
class CustomAuthStore extends LocalCookieAuthStore {
_originalGenerateUserId;
constructor(...args: ConstructorParameters<typeof LocalCookieAuthStore>) {
super(...args);
this._originalGenerateUserId = this.generateUserId;
this.generateUserId = () => {
return window.areCookiesAccepted
? this._originalGenerateUserId()
: `cookieless${new Date().toISOString().substring(0, 13)?.replace(/-/g, '')}`;
};
}
get user(): UserRecord {
const existingUser = super.user;
if (!existingUser) return null;
const isCookieless = existingUser.userId.startsWith('cookieless');
// Was cookieless, now accepted → clear so a real userId gets generated
if (isCookieless && window.areCookiesAccepted) {
this.clear();
// By returning null, generateUserId() will be called again
return null;
}
// Was real userId, now rejected → clear so a cookieless id gets generated
if (!isCookieless && !window.areCookiesAccepted) {
this.clear();
// By returning null, generateUserId() will be called again
return null;
}
return existingUser;
}
}
const xg = new XGenClient({
key: '',
secret: '',
clientId: '',
trackerId: '',
authStore: new CustomAuthStore(),
});