Skip to main content
This page documents an earlier version of the API client. For the latest version, see Customize the API clients.
To change individual requests made with an API client, see Request options. To change all requests, create a custom configuration. This lets you change timeouts, HTTP headers, and other settings.

Custom hosts

You can change the default hosts to which the API client connects:
SearchConfig config = new SearchConfig("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY")
{
    CustomHosts = new List<StatefulHost>
    {
        new StatefulHost
        {
            Url = "yourapplication.example.net",
            Up = true,
            LastUse = DateTime.UtcNow,
            Accept = CallType.Read | CallType.Write,
        },
    }
};

SearchClient client = new SearchClient(config);
Changing the hosts can be useful if you want to proxy the search requests through another server, for example, to process the request or response, or to perform custom analytics.

Add HTTP headers to every request

Adding HTTP headers to your requests lets you set parameters such as a user identifier or an IP address. This can be useful for analytics, geographical search, or applying API key rate limits.
var configuration = new SearchConfig("undefined", "undefined");
configuration.DefaultHeaders.Add("NAME-OF-HEADER", "value-of-header");

SearchClient client = new SearchClient(configuration);
You can add these headers to your requests:
HeaderUse cases
X-Algolia-UserToken
  • API key rate limits
  • Identifies users for the Analytics API. Overrides X-Forwarded-For. Use to forward user identity without relying on IP addresses.
X-Forwarded-For
  • For backend analytics, forward the user’s IP address. Otherwise, analytics uses your server’s IP and treats all users as a single user.
  • For backend location (geo) searches, set to the user’s IP to ensure accurate geolocation. Otherwise, the server’s IP is used.

Add custom headers to individual requests

Index index = client.InitIndex("ALGOLIA_INDEX_NAME");

RequestOptions requestOptions = new RequestOptions
{
    Headers = new Dictionary<string,string>{ { "X-Algolia-UserToken", "user123" } }
};

var result = index.Search<Result>(new Query("query string"), requestOptions);
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).

Change timeouts for all requests

Network connections and DNS resolution can be slow. That’s why the API clients come with default timeouts.
var configuration = new SearchConfig("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY")
{
  ConnectTimeout = 15, // connection timeout in seconds
  ReadTimeout = 5, // read timeout in seconds
  WriteTimeout = 30, // write timeout in seconds
  HostDownDelay = 300 // delay before retrying a host that was down, in seconds (= 5 minutes)
};

Change timeouts for individual requests

Index index = client.InitIndex("ALGOLIA_INDEX_NAME");

RequestOptions requestOptions = new RequestOptions
{
  // Set the readTimeout to 20 seconds
  Timeout = 20
};

var result = index.Search<Result>(new Query("query string"), requestOptions);

Further customization options for JavaScript

This section describes more customization options for the JavaScript API clients.

Change authentication mode

The JavaScript Search API client lets you change how you send your credentials to Algolia. You can set the authmode option to:
  • WithinHeaders to send the credentials as headers
  • WithinQueryParameters to send the credentials as URL query parameters.
This option only works with search-related API requests. Since it doesn’t perform a preflight request, you should only use it in frontend implementations.
JavaScript
import { AuthMode } from "@algolia/client-common";

const algoliasearch = algoliasearch(
  "ALGOLIA_APPLICATION_ID",
  "ALGOLIA_API_KEY",
  {
    authMode: AuthMode.WithinHeaders,
    // authMode: AuthMode.WithinQueryParameters
  },
);
The default depends on the environment:
  • algoliasearch/lite (browser): WithinQueryParameters
  • algoliasearch (browser): WithinHeaders
  • algoliasearch (Node): WithinHeaders

Cache requests and responses

The client caches requests to Algolia and their responses. You can change the location of your caches, or turn off caching completely. If you build your own cache, you must use the Cache type from @algolia/cache-common. The following cache types are available:
  • NullCache. No caching for requests and responses. Every method call makes an API request.
  • InMemoryCache. The client stores requests and responses in memory. When you perform the same query again during your search session, the client reads the results from the cache instead of making a new API request. This avoids duplicate API calls, for example, when a user deletes characters from their current query. Similarly, the client retrieves results from the response cache for queries that you’ve already performed during your search session. The InMemoryCache resets on page refresh.
  • LocalStorageCache. The client stores requests and responses in localStorage. When you perform the same query again while the value is still active, the client reads the results from the cache instead of making a new API request. This avoids duplicate API calls, for example, when a user refreshes a page. The LocalStorageCache resets values when their TTL has been reached. When local storage isn’t available, for example, when browsing in private mode, it’s better to use BrowserLocalStorageCache inside FallbackableCache.
  • FallbackableCache. An option to conditionally select one of the other cache types.
These caches are used for:
  • responsesCache. Caches responses from Algolia. The client stores the response for a query and returns it when you perform the same query again.
  • requestsCache. Caches promises with the same request payload. The client stores the promise for a request and returns it when you perform the same request again, while the previous request is still pending.
JavaScript
import { createNullCache } from "@algolia/cache-common";
import { createInMemoryCache } from "@algolia/cache-in-memory";
import { createFallbackableCache } from "@algolia/cache-common";
import { createBrowserLocalStorageCache } from "@algolia/cache-browser-local-storage";

const algoliasearch = algoliasearch(
  "ALGOLIA_APPLICATION_ID",
  "ALGOLIA_API_KEY",
  {
    // Caches responses from Algolia
    responsesCache: createInMemoryCache(),
    // or another cache, like browserLocalStorageCache
    responsesCache: createFallbackableCache({
      caches: [
        createBrowserLocalStorageCache({
          key: `algolia-responses-${"ALGOLIA_APPLICATION_ID"}-${1}`,
          timeToLive: 60,
        }),
        createInMemoryCache(),
      ],
    }),

    // Caches Promises with the same request payload
    requestsCache: createInMemoryCache({ serializable: false }), // or another cache
  },
);
The default cache depends on the environment:
  • algoliasearch/lite (browser): InMemoryCache
  • algoliasearch (browser): InMemoryCache
  • algoliasearch (Node): NullCache

Cache the state of hosts

The JavaScript API client stores the state of hosts between search requests. This helps to avoid unreachable hosts. The state of the hosts remains in the cache for 2 minutes when the host is down. Whenever a host times out, the API client pushes it to the end of the list of hosts to query on the next request. You can build a custom cache for hosts as long as it respects the Cache type from @algolia/cache-common. The following cache types are available:
  • NullCache. No caching for hosts.
  • InMemoryCache. The client stores the state of hosts in memory. The cache resets on page refresh.
  • BrowserLocalStorageCache. The client stores the state of hosts in the local storage. Refreshing the page doesn’t reset the cache. When local storage isn’t available, for example, when browsing in private mode, it’s better to use BrowserLocalStorageCache inside FallbackableCache.
  • FallbackableCache. An option to conditionally select one of the other cache types.
JavaScript
import { createFallbackableCache } from "@algolia/cache-common";
import { version } from "@algolia/client-common";
import { createInMemoryCache } from "@algolia/cache-in-memory";
import { createBrowserLocalStorageCache } from "@algolia/cache-browser-local-storage";

const algoliasearch = algoliasearch(
  "ALGOLIA_APPLICATION_ID",
  "ALGOLIA_API_KEY",
  {
    hostsCache: createFallbackableCache({
      caches: [
        createBrowserLocalStorageCache({ key: `${version}-${appId}` }),
        createInMemoryCache(),
      ],
    }), // or createNullCache(), createInMemoryCache()
  },
);
The default depends on the environment:
  • algoliasearch/lite (browser): FallbackableCache(BrowserLocalStorageCache, InMemoryCache)
  • algoliasearch (browser): FallbackableCache(BrowserLocalStorageCache, InMemoryCache)
  • algoliasearch (Node): InMemoryCache
For more information, see Retries and fallback logic.

Logging

The logger option helps you understand more about what’s going on with the client. It accepts any implementation that respects the Logger type from @algolia/logger-common. These loggers are available:
  • NullLogger. The client doesn’t log anything.
  • ConsoleLogger.The client logs events with console.log.
JavaScript
import { createNullLogger, LogLevelEnum } from "@algolia/logger-common";
import { createConsoleLogger } from "@algolia/logger-console";

const algoliasearch = algoliasearch(
  "ALGOLIA_APPLICATION_ID",
  "ALGOLIA_API_KEY",
  {
    logger: createConsoleLogger(LogLevelEnum.Debug), // or createNullLogger
  },
);
The client only logs failures that can be retried. This helps detect anomalies when connecting to Algolia. The default depends on the environment:
  • algoliasearch/lite (browser): ConsoleLogger(LogLevelEnum.Error)
  • algoliasearch (browser): ConsoleLogger(LogLevelEnum.Error)
  • algoliasearch (Node): NullLogger

Change HTTP request methods

Use the requester option to specify how the client makes network requests. Your custom implementation must respect the Requester type from @algolia/requester-common. The following request methods are available:
JavaScript
import { createBrowserXhrRequester } from "@algolia/requester-browser-xhr";
import { createNodeHttpRequester } from "@algolia/requester-node-http";
import { createFetchRequester } from "@algolia/requester-fetch";

const algoliasearch = algoliasearch(
  "ALGOLIA_APPLICATION_ID",
  "ALGOLIA_API_KEY",
  {
    requester: createBrowserXhrRequester(), // or alternatively:
    // requester: createNodeHttpRequester(),
    // requester: createFetchRequester(),
  },
);
The default depends on the environment:
  • algoliasearch/lite (browser): BrowserXhrRequester
  • algoliasearch (browser): BrowserXhrRequester
  • algoliasearch (Node): NodeHttpRequester

Custom user agents

You can use a custom userAgent for interacting with Algolia. This is useful when you’re building an integration on top of algoliasearch, or when building custom clients.

Add to the default user agent

Add a string to the default user agent:
JavaScript
const searchClient = algoliasearch("ALGOLIA_API_KEY", "ALGOLIA_API_KEY");

searchClient.addAlgoliaAgent("CustomSegment", "x.y.z");
This sets the user agent to:
Algolia for JavaScript (a.b.c); Browser; CustomSegment (x.y.z)
The client uses the following userAgent by default:
  • algoliasearch/lite (browser): Algolia for JavaScript (a.b.c); Browser (lite);
  • algoliasearch (browser): Algolia for JavaScript (a.b.c); Browser;
  • algoliasearch (Node): Algolia for JavaScript (a.b.c); Node.js;

Replace the default user agent

Replace the user agent information by using the createUserAgent function:
JavaScript
// `version` contains a string with the format "a.b.c"
import { version } from "@algolia/client-common";
import { createUserAgent } from "@algolia/transporter";

const searchClient = algoliasearch(
  "ALGOLIA_APPLICATION_ID",
  "ALGOLIA_INDEX_NAME",
  {
    userAgent: createUserAgent(version).add({
      segment: "CustomSegment",
      version: "x.y.z",
    }),
  },
);
This sets the user agent to:
Algolia for JavaScript (a.b.c); CustomSegment (x.y.z);
Note how this removes the environment (“Browser” or “Node.js”) from the user agent string. By default, userAgent is:
  • algoliasearch/lite (browser): Algolia for JavaScript (x.x.x); Browser (lite);
  • algoliasearch (browser): Algolia for JavaScript (x.x.x); Browser;
  • algoliasearch (Node): Algolia for JavaScript (x.x.x); Node.js;

Keep-alive connections

By default, the JavaScript API client sends requests with the Keep-Alive header: Connection: keep-alive. To close all remaining connections after you’re done interacting with the Algolia API, use client.destroy():
JavaScript
const client = algoliasearch("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY");
const index = client.initIndex("ALGOLIA_INDEX_NAME");

const results = await index.search("query string");

await client.destroy();

Build an API client from scratch

For full control, create your API client from scratch with the createSearchClient function.
JavaScript
import { createBrowserLocalStorageCache } from "@algolia/cache-browser-local-storage";
import { createFallbackableCache } from "@algolia/cache-common";
import { createInMemoryCache } from "@algolia/cache-in-memory";
import { AuthMode, version } from "@algolia/client-common";
import { createSearchClient, multipleQueries } from "@algolia/client-search";
import { LogLevelEnum } from "@algolia/logger-common";
import { createConsoleLogger } from "@algolia/logger-console";
import { createBrowserXhrRequester } from "@algolia/requester-browser-xhr";
import { createUserAgent } from "@algolia/transporter";

const client = createSearchClient({
  appId: "ALGOLIA_APPLICATION_ID",
  apiKey: "ALGOLIA_API_KEY",
  timeouts: {
    connect: 1,
    read: 2,
    write: 30,
  },
  requester: createBrowserXhrRequester(),
  logger: createConsoleLogger(LogLevelEnum.Error),
  responsesCache: createInMemoryCache(),
  requestsCache: createInMemoryCache({ serializable: false }),
  hostsCache: createFallbackableCache({
    caches: [
      createBrowserLocalStorageCache({ key: `${version}-${appId}` }),
      createInMemoryCache(),
    ],
  }),
  userAgent: createUserAgent(version).add({
    segment: "Browser",
    version: "lite",
  }),
  authMode: AuthMode.WithinQueryParameters,
  methods: { search: multipleQueries },
});

Pass options to the PHP HTTP client

The PHP API client lets you override what HTTP layer will be used by the search client. You can pass custom options to the underlying HTTP client, for example, to configure a proxy. Choose between these two HTTP clients:
  • Guzzle, a popular HTTP client for PHP (recommended)
  • A custom HTTP client built on top of curl

Guzzle HTTP client

See guzzle options
PHP
<?php
use Algolia\AlgoliaSearch\Algolia;
use GuzzleHttp\Client as GuzzleClient;

$httpClient = new Algolia\AlgoliaSearch\Http\Guzzle6HttpClient(
  new GuzzleClient([
    'proxy' => $proxyAddress,
  ])
);

Algolia::setHttpClient($httpClient);

Default HTTP client based on curl

See curl options.
PHP
<?php
use Algolia\AlgoliaSearch\Algolia;

$httpClient = new Algolia\AlgoliaSearch\Http\Php53HttpClient([
    'CURLOPT_PROXY' => $strProxy,
    'CURLOPT_FOLLOWLOCATION' => 1,
]);

Algolia::setHttpClient($httpClient);
I