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 identifiers once users sign in.

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 }) {
    // ...
  },
});

// Set anonymous user token
window.aa("setUserToken", "anonymous-user-123");

// Set authenticated user token
window.aa("setAuthenticatedUserToken", "authenticated-user-123");

If you’re using React InstantSearch, 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

Make sure to use the same user token for your events (Insights API) and search requests (Search API).

  • If you send the authenticatedUserToken with your events, send the same value with your search requests.
  • If you send the userToken with your events, send the same value with your search requests.

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?