Guides / Getting analytics / Search analytics / Out-of-the-box analytics

How to Set the Analytics UserToken

For query aggregation, Search Analytics, and Personalization to work properly, the analytics engine needs to uniquely identify each of your users. You can do this with the userToken parameter.

It’s best to explicitly create a reliable unique identifier that you store in your application or database. For example, you can use your own user identifiers once users log in.

When using one of the API clients, you need to:

  • set the userToken search parameter to tell Algolia which user is searching,
  • or set the X-Forwarded-For header to forward Algolia the user’s IP address if you perform the search from your back end.

Set the userToken search parameter

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

During client initialization

1
2
3
4
5
6
$config = \Algolia\AlgoliaSearch\Config\SearchConfig::create('YourApplicationID', 'YourSearchOnlyAPIKey');
$config->setDefaultHeaders([
    'X-Algolia-UserToken' => '123456',
]);

$client = \Algolia\AlgoliaSearch\SearchClient::createWithConfig($config);

Using InstantSearch

1
2
3
4
5
6
7
8
9
const insightsMiddleware = instantsearch.middlewares.createInsightsMiddleware({
  insightsClient,
  onEvent,
});

search.use(insightsMiddleware);

// See https://www.algolia.com/doc/api-reference/widgets/insights/js/
// for more information about `insights` middleware.

Set the X-Forwarded-For header

You only have to set this header if you perform your search from your back end. Please make sure to replace the IP address in the snippet with the actual IP address of your end user.

1
2
3
4
5
$index = $client->initIndex('your_index_name');

$res = $index->search('query string', [
    'X-Forwarded-For' => '94.228.178.246',
]);

Did you find this page helpful?