Search analytics / Guides

Distinguish users for analytics

By default, Algolia uses the IP address to distinguish users. For more accurate analytics, you can explicitly set a user token. This is especially important if you’re searching from your backend, as all searches would have the IP address of your server.

It’s best to create reliable unique identifiers that you store in your app or database. For example, you could use your own user session identifiers once users start their session.

You must send a user token with your search requests if you use Personalization.

Set the user token in InstantSearch and Autocomplete

If you’re using Autocomplete, InstantSearch.js, React InstantSearch, or Vue InstantSearch, set the insights option to true when initializing the library.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import { autocomplete } from "@algolia/autocomplete-js";
import algoliasearch from "algoliasearch/lite";

const appID = "YourApplicationID"
const apiKey = "YourSearchAPIKey"

const searchClient = algoliasearch(appID, apiKey);

autocomplete({
  container: "#autocomplete",
  placeholder: "Search ...",
  insights: true,
  getSources({ query }) {
    // ...
  },
});

// You can also use insights to set an anonymous user token
window.aa("setUserToken", "anonymous-user-123");

// You can also use insights to set an authenticated user token
window.aa("setAuthenticatedUserToken", "authenticated-user-123");

If you’re using Angular InstantSearch, InstantSearch iOS, or InstantSearch Android, add the userToken as an API parameter to your search requests:

1
2
3
4
5
6
7
val query = query {
    userToken {
        'test-user-123'
    }
}

val searcher = HitsSearcher(client, indexName, query)

Set the user token with API clients

The user token should match the userToken in events sent to the Insights API (also known as the anonymous user token, or session user token).

To set the user token per search request:

1
$index->search('query', ['userToken' => '123456'])

To set the user token when initializing the API client:

1
2
3
4
5
6
7
8
9
use \Algolia\AlgoliaSearch\Config\SearchConfig
use \Algolia\AlgoliaSearch\SearchClient

$config = SearchConfig::create('YourApplicationID', 'YourSearchOnlyAPIKey');
$config->setDefaultHeaders([
    'X-Algolia-UserToken' => 'test-user-123',
]);

$client = SearchClient::createWithConfig($config);

If you search from your backend and don’t want to set a userToken, you can forward user IP addresses.

Did you find this page helpful?