Customize your JavaScript client
You can customize the behavior of the API clients by creating a custom configuration This lets you change timeouts, or add HTTP headers.
To modify all requests made with a client, create a custom configuration. To modify individual requests, pass custom request options.
We released a new version of the JavaScript API client in public beta. Read the beta documentation for more information.
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 configuration allow you to set parameters for every request, for example, a user identifier or an IP address. This can be useful for analytics, geographic searches, or to implement API key rate limits.
For an overview of available HTTP headers, see Add HTTP headers to your requests
1
2
3
4
5
const client = algoliasearch('YourApplicationID', 'YourWriteAPIKey', {
headers: {
'NAME-OF-HEADER': 'value-of-header'
}
});
Add query parameters
Similar to headers, 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.
You shouldn’t change the default timeouts, unless you have a good reason.
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
}
});
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 this option doesn’t perform a preflight request, you should only use this 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.
You can also build your own cache which 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.The browser’s local storage isn’t always available, for example, when browsing in private mode.
It’s better to use
BrowserLocalStorageCache
insideFallbackableCache
with an alternative, when the local storage isn’t available. -
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 avoiding 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. The browser’s local storage isn’t always available, for example, when browsing in private mode. It’s better to useBrowserLocalStorageCache
insideFallbackableCache
with an alternative, when the local storage isn’t available.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 within 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 retryable failures. This helps detecting 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
You can use the requester
option to specify how the client makes network requests.
You can build a custom implementation that 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
You can replace the user agent completely 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, you can 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 },
});