🎉 Try the public beta of the new docs site at algolia.com/doc-beta! 🎉
API client / Methods / Insights

This method is only available for JavaScript.

Required API Key: any key with the search ACL
Method signature
Only available for JavaScript

We released a new version of the PHP API client in public beta. Read the beta documentation for more information.

We released a new version of the Java API client in public beta. Read the beta documentation for more information.

You’re currently reading the Ruby API client v2 documentation. Check the migration guide to learn how to upgrade from v1 to v2. You can still access the v1 documentation.

About this method

Set the user token for all subsequent events sent to the Algolia Insights API.

Use this method to automatically send the userToken with every event.

Examples

Read the Algolia CLI documentation for more information.

The following example initializes the Insights API client aa. If the user isn’t identified initially, you can let the Insights API client generate an anonymous user token, and persist it in the cookies with the useCookie option.

For more information on how to initialize the aa object, refer to Initialize the Insights client.

1
2
3
4
5
aa('init', {
  appId: 'YourApplicationID',
  apiKey: 'YourSearchOnlyAPIKey',
  useCookie: true,
});

Then, keep track of the anonymous user token generated by the Insights API Client to restore it when the user logs out.

1
2
3
4
5
6
7
8
9
10
let anonymousUserToken;

aa('getUserToken', {}, (err, userToken) => {
  if (err) {
    console.error(err);
    return;
  }

  anonymousUserToken = userToken;
});

When the user logs in, synchronize the user token with the user ID coming from your system.

1
aa('setUserToken', 'YourUserID');

Finally, when the user logs out, restore the anonymous user token.

1
2
3
if (anonymousUserToken) {
  aa('setUserToken', anonymousUserToken);
}

Parameters

userToken
type: string
pattern: [A-Za-z0-9_=+/-]{1,129}

Pseudonymous or anonymous user identifier.

Never include personal identifiable information in user tokens.

See also: User Token

Response

This method doesn't return a response.

Did you find this page helpful?