Skip to content

Commit

Permalink
fix: save existing anon tokens for multiple init calls (#562)
Browse files Browse the repository at this point in the history
### Context

In InstantSearch, in order for user tokens to be set in time for the
first query on page load, anonymous user tokens are generated and set as
both the InstantSearch token and Insights token.

This flow has one issue though. When `useCookies` flag needs to be
changed later (such as with a cookie consent banner), a second `init`
call to insights with the flag set to true does not save the existing
token to a cookie.

A short repro is as follows with the very latest version of
InstantSearch where this behaviour was added (PR:
algolia/instantsearch#6377):

```js
const searchClient = algoliasearch(
  // ...
);

window.aa('init', {
  appId: 'id',
  apiKey: 'key',
});

const search = instantsearch({
  indexName: 'index',
  searchClient,
  insights: true,
});

search.addWidgets([
  // ...
]);

// This does not save the cookie atm
setTimeout(() => {
  window.aa('init', {
    partial: true,
    useCookie: true,
  });
}, 5000);
```
  • Loading branch information
shaejaz authored Oct 31, 2024
1 parent e9a4c10 commit 86164bb
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 2 deletions.
18 changes: 18 additions & 0 deletions lib/__tests__/init.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { getCookie, MONTH } from "../_tokenUtils";
import AlgoliaAnalytics from "../insights";
import * as utils from "../utils";
import { createUUID } from "../utils/uuid";

jest.mock("../utils", () => ({
__esModule: true,
Expand Down Expand Up @@ -240,6 +241,23 @@ describe("init", () => {

setUserToken.mockRestore();
});
it("should save anonymous userToken as cookie when useCookie is set to true later", () => {
analyticsInstance.init({
apiKey: "***",
appId: "XXX"
});

analyticsInstance.setUserToken(`anonymous-${createUUID()}`);

analyticsInstance.init({
partial: true,
useCookie: true
});

expect(document.cookie).toEqual(
expect.stringMatching(/^_ALGOLIA=anonymous-/)
);
});
it("should replace existing options when called again", () => {
analyticsInstance.init({
apiKey: "apiKey1",
Expand Down
18 changes: 18 additions & 0 deletions lib/_tokenUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,24 @@ export const getCookie = (name: string): string => {
return "";
};

export function checkIfAnonymousToken(token: number | string): boolean {
if (typeof token === "number") {
return false;
}

return token.indexOf("anonymous-") === 0;
}

export function saveTokenAsCookie(this: AlgoliaAnalytics): void {
const foundToken = getCookie(COOKIE_KEY);
if (
this._userToken &&
(!foundToken || foundToken === "" || foundToken.indexOf("anonymous-") !== 0)
) {
setCookie(COOKIE_KEY, this._userToken, this._cookieDuration);
}
}

export function setAnonymousUserToken(
this: AlgoliaAnalytics,
inMemory = false
Expand Down
16 changes: 15 additions & 1 deletion lib/init.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { DEFAULT_ALGOLIA_AGENTS } from "./_algoliaAgent";
import { MONTH } from "./_tokenUtils";
import { checkIfAnonymousToken, MONTH } from "./_tokenUtils";
import type AlgoliaAnalytics from "./insights";
import { isUndefined, isNumber } from "./utils";

Expand Down Expand Up @@ -80,6 +80,8 @@ You can visit https://algolia.com/events/debugger instead.`);
this.setUserToken(options.userToken);
} else if (!this._userToken && !this._userHasOptedOut && this._useCookie) {
this.setAnonymousUserToken();
} else if (checkIfTokenNeedsToBeSaved(this)) {
this.saveTokenAsCookie();
}
}

Expand Down Expand Up @@ -110,3 +112,15 @@ function setOptions(
)
);
}

function checkIfTokenNeedsToBeSaved(target: AlgoliaAnalytics): boolean {
if (target._userToken === undefined) {
return false;
}

return (
checkIfAnonymousToken(target._userToken) &&
target._useCookie &&
!target._userHasOptedOut
);
}
5 changes: 4 additions & 1 deletion lib/insights.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ import {
MONTH,
setAuthenticatedUserToken,
onAuthenticatedUserTokenChange,
getAuthenticatedUserToken
getAuthenticatedUserToken,
saveTokenAsCookie
} from "./_tokenUtils";
import {
clickedObjectIDsAfterSearch,
Expand Down Expand Up @@ -78,6 +79,7 @@ class AlgoliaAnalytics {
getVersion: typeof getVersion;
addAlgoliaAgent: typeof addAlgoliaAgent;

saveTokenAsCookie: typeof saveTokenAsCookie;
setUserToken: typeof setUserToken;
setAnonymousUserToken: typeof setAnonymousUserToken;
getUserToken: typeof getUserToken;
Expand Down Expand Up @@ -110,6 +112,7 @@ class AlgoliaAnalytics {

this.addAlgoliaAgent = addAlgoliaAgent.bind(this);

this.saveTokenAsCookie = saveTokenAsCookie.bind(this);
this.setUserToken = setUserToken.bind(this);
this.setAnonymousUserToken = setAnonymousUserToken.bind(this);
this.getUserToken = getUserToken.bind(this);
Expand Down

0 comments on commit 86164bb

Please sign in to comment.