How to Set the Analytics User Id

For analytics query aggregation to work properly, the analytics engine relies on a user id.

By default, we will use the user’s IP address as the userToken, but it can be any unique identifier sent by you. For example, you could use a unique id you store in a database.

When using a back-end API client, you want to either:

  • set the X-Forwarded-For header to forward the user IP to Algolia
  • set the X-Algolia-UserToken header to tell Algolia which user is querying

Forward the user IP

1
2
3
4
5
6
7
8
9
10
11
12
13
// '94.228.178.246' should be replaced with the actual IP you would like
// to search around. Depending on your stack there are multiple ways to get this
// information.
// This is only needed when you're making a request from the backend. If you make
// your request in the browser, then this is added automatically.


$index = $client->initIndex('your_index_name');

$res = $index->search('query string', [
  'hitsPerPage' => 10, // search parameter
  'X-Forwarded-For' => '94.228.178.246' // extra header
]);

Forward the user token

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

$res = $index->search('query string', [
  'hitsPerPage' => 10, // search parameter
  'X-Algolia-UserToken' => 'user123' // extra header
]);

Did you find this page helpful?