Customize your JavaScript client
This is documentation for v4 of the JavaScript API clients, which is not the latest version. To see the documentation for the latest version, see JavaScript v5.
To change individual requests made with an API client, pass individual Add request options. To change all requests, create a custom configuration. This lets you change timeouts, add HTTP headers, and so on.
Use a custom host
You can change the default hosts to which the API client connects:
1
2
3
4
5
6
7
8
9
10
// Default version
import algoliasearch from 'algoliasearch';
// Search-only version
// import algoliasearch from 'algoliasearch/lite';
const client = algoliasearch('YourApplicationID', 'YourWriteAPIKey', {
hosts: [{ url: 'yourapplication.example.net' }],
});
const index = client.initIndex('your_index_name');
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.
1
2
3
4
5
const client = algoliasearch('YourApplicationID', 'YourWriteAPIKey', {
headers: {
'NAME-OF-HEADER': 'value-of-header'
}
});
You can add these headers to your requests:
Header | Use case |
---|---|
X-Algolia-UserToken |
Use API key rate limits |
X-Algolia-UserToken |
The Analytics API uses the value of this header to distinguish between users. It takes priority over any value in X-Forwarded-For . Use the X-Algolia-UserToken header to forward the user’s identity without relying on IP addresses. |
X-Forwarded-For |
Use for analytics in backend implementations. If your server sends the user’s IP address with every search, analytics can distinguish between users. Otherwise, the analytics uses the server’s IP address and considers all your users as a single user. |
X-Forwarded-For |
Use for geolocation, when you perform searches from your backend. This ensures that the geolocation for a search uses your user’s IP address and not that of your server. |
1
2
3
4
5
6
7
8
9
10
const index = client.initIndex('indexName');
const requestOptions = {
headers: { 'X-Algolia-UserToken': 'user123' }
}
index.search('query string', requestOptions)
.then(({ hits }) => {
console.log(hits);
});
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.
Add query parameters
You can add query parameters to all requests, by specifying them in the client options:
1
2
3
4
5
6
7
8
9
const algoliasearch = algoliasearch(
'YourApplicationID',
'YourSearchOnlyAPIKey',
{
queryParameters: {
'NAME-OF-QUERY-PARAMETER': 'value-of-query-parameter',
},
},
);
Change timeouts for all requests
Network connections and DNS resolution can be slow. That’s why the API clients come with default timeouts.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const client = algoliasearch(appId, apiKey, {
timeouts: {
connect: 2, // connection timeout in seconds
read: 5, // read timeout in seconds
write: 30 // write timeout in seconds
}
});
const analytics = client.initAnalytics({
timeouts: {
connect: 2, // connection timeout in seconds
read: 5, // read timeout in seconds
write: 30 // write timeout in seconds
}
});
const personalization = client.initPersonalization({
timeouts: {
connect: 2, // connection timeout in seconds
read: 5, // read timeout in seconds
write: 30 // write timeout in seconds
}
});
Don’t change the default timeouts without a good reason.
1
2
3
4
5
6
7
8
9
10
11
const index = client.initIndex('indexName');
const requestOptions = {
// Set the readTimeout to 20 seconds
timeouts: { read: 20 }
}
index.search('query string', requestOptions)
.then(({ hits }) => {
console.log(hits);
});
Change authentication mode
The JavaScript 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 headersWithinQueryParameters
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.
1
2
3
4
5
6
7
8
9
10
import { AuthMode } from '@algolia/client-common';
const algoliasearch = algoliasearch(
'YourApplicationID',
'YourSearchOnlyAPIKey',
{
authMode: AuthMode.WithinHeaders,
// authMode: AuthMode.WithinQueryParameters
},
);
The default depends on the environment:
algoliasearch/lite
(browser):WithinQueryParameters
algoliasearch
(browser):WithinHeaders
algoliasearch
(Node):WithinHeaders
Caching 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. TheInMemoryCache
resets on page refresh. -
LocalStorageCache
. The client stores requests and responses inlocalStorage
. 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
insideFallbackableCache
. -
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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(
'YourApplicationID',
'YourSearchOnlyAPIKey',
{
// Caches responses from Algolia
responsesCache: createInMemoryCache(),
// or another cache, like browserLocalStorageCache
responsesCache: createFallbackableCache({
caches: [
createBrowserLocalStorageCache({
key: `algolia-responses-${'YourApplicationID'}-${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
Caching the state of hosts
The JavaScript API client stores the state of hosts between search requests. This helps 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 useBrowserLocalStorageCache
insideFallbackableCache
.FallbackableCache
. An option to conditionally select one of the other cache types.
1
2
3
4
5
6
7
8
9
10
11
12
13
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(appId, 'YourSearchOnlyAPIKey', {
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
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 withconsole.log
.
1
2
3
4
5
6
7
8
9
10
import { createNullLogger, LogLevelEnum } from '@algolia/logger-common';
import { createConsoleLogger } from '@algolia/logger-console';
const algoliasearch = algoliasearch(
'YourApplicationID',
'YourSearchOnlyAPIKey',
{
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
Changing 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:
BrowserXhrRequester
uses XMLHttpRequest.NodeHttpRequester
uses the native HTTP Node.js module.FetchRequester
uses the fetch.
1
2
3
4
5
6
7
8
9
10
11
12
13
import { createBrowserXhrRequester } from '@algolia/requester-browser-xhr';
import { createNodeHttpRequester } from '@algolia/requester-node-http';
import { createFetchRequester } from '@algolia/requester-fetch';
const algoliasearch = algoliasearch(
'YourApplicationID',
'YourSearchOnlyAPIKey',
{
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 a custom client.
Add to the default user agent
You can add a string to the default user agent:
1
2
3
4
5
6
const searchClient = algoliasearch(
'YourApplicationID',
'YourSearchOnlyAPIKey'
);
searchClient.addAlgoliaAgent('CustomSegment', 'x.y.z');
This sets the user agent to:
1
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
Completely replace the user agent by using the createUserAgent
function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// `version` contains a string with the format "a.b.c"
import { version } from '@algolia/client-common';
import { createUserAgent } from '@algolia/transporter';
const searchClient = algoliasearch(
'YourApplicationID',
'YourSearchOnlyAPIKey',
{
userAgent: createUserAgent(version).add({
segment: 'CustomSegment',
version: 'x.y.z',
}),
},
);
This sets the user agent to:
1
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 set to:
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
. The process doesn’t exit, even if you don’t perform any further operations.
To close all remaining connections after you’re done interacting with the Algolia API, use client.destroy()
:
1
2
3
4
5
6
const client = algoliasearch('YourApplicationID', 'YourWriteAPIKey');
const index = client.initIndex('your_index_name');
const results = await index.search('query string');
await client.destroy();
Keep alive is always activated in browsers.
Build an API client from scratch
For full control, create your API client from scratch with the createSearchClient
function.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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: 'YourApplicationID',
apiKey: 'YourSearchOnlyAPIKey',
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 },
});