Configure the client
The JavaScript client was built with modularity in mind and offers many configuration options.
The client ships with default settings that work out-of-the-box for 99% of use cases. This guide covers the remaining 1%: customizing timeout values, your cache implementation, or the requester. Modifying default settings can have negative effects in certain environments, so make sure to know what you’re doing.
Auth mode
With the authMode
option, you can set how you send credentials to Algolia.
WithinHeaders
: uses the request headers.WithinQueryParameters
: uses the request URL query parameters. This option only works with search-related methods. We only recommend it for front-end implementations, since it doesn’t perform a preflight request.
1
2
3
4
5
6
7
8
9
import { AuthMode } from '@algolia/client-common';
const algoliasearch = algoliasearch(
'YourApplicationID',
'YourSearchOnlyAPIKey',
{
authMode: AuthMode.WithinHeaders, // or AuthMode.WithinQueryParameters
},
);
By default, authMode
is set to:
algoliasearch/lite
(browser):WithinQueryParameters
algoliasearch
(browser):WithinHeaders
algoliasearch
(Node):WithinHeaders
Cache on requests and responses
The client caches requests to Algolia and their responses. You can configure the location of your caches, or disable them. You can also build your own cache as long as your implementation respects the Cache
type from @algolia/cache-common
.
- With
NullCache
, the client doesn’t store requests or responses. Each request, even if repeated, fires an API search call. - With
InMemoryCache
, the client stores both requests and responses in memory. When you perform the same query again during your search session, the client reads the results from the requests cache instead of firing a new search request. This avoids useless or duplicate API calls, which can happen, 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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { createNullCache } from '@algolia/cache-common';
import { createInMemoryCache } from '@algolia/cache-in-memory';
const algoliasearch = algoliasearch(
'YourApplicationID',
'YourSearchOnlyAPIKey',
{
// Caches responses from Algolia
responsesCache: createInMemoryCache(), // or createNullCache()
// Caches Promises with the same request payload
requestsCache: createInMemoryCache({ serializable: false }), // or createNullCache()
},
);
By default, responsesCache
and requestsCache
are set to:
algoliasearch/lite
(browser):InMemoryCache
algoliasearch
(browser):InMemoryCache
algoliasearch
(Node):NullCache
Cache on hosts
As with requestsCache
and responsesCache
, the hostsCache
option lets the client store the state of hosts between search requests, allowing it to avoid targeting unavailable hosts. The state of the hosts remains in the cache for 2 minutes when the host is down. Whenever a host times out, the client pushes it to the end of the list of hosts to query on the next request.
You can build a custom implementation as long as it respects the Cache
type from @algolia/cache-common
.
- With
NullCache
, the client doesn’t store the state of hosts. Therefore, if a host is not available, the next request may end up retargeting it. We don’t recommend this approach. - With
InMemoryCache
, the client stores the state of hosts in memory. The cache resets on page refresh. - With
BrowserLocalStorageCache
, the client stores the state of hosts in the local storage. Refreshing the page doesn’t reset the cache. - With
FallbackableCache
, you can pass all options above, allowing you to specify what cache takes over whenever something fails.
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()
});
Don’t use the BrowserLocalStorageCache
on its own. In certain conditions, such as private browsing, the local storage is unaccessible. Instead, use FallbackableCache
to provide an alternative for when the local storage isn’t available.
By default, hostsCache
is set to:
algoliasearch/lite
(browser):FallbackableCache(BrowserLocalStorageCache, InMemoryCache)
algoliasearch
(browser):FallbackableCache(BrowserLocalStorageCache, InMemoryCache)
algoliasearch
(Node):InMemoryCache
Logger
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
.
- With
NullLogger
, the client doesn’t log anything. - With
ConsoleLogger
, the client logs events usingconsole.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 currently logs retryable failures only. This is useful for detecting anomalies when connecting to Algolia.
By default, logger
is set to:
algoliasearch/lite
(browser):ConsoleLogger(LogLevelEnum.Error)
algoliasearch
(browser):ConsoleLogger(LogLevelEnum.Error)
algoliasearch
(Node):NullLogger
Requester
The way you perform network requests should depend on your environment. You can use the requester
option to specify how the client makes network requests. You can build a custom implementation as long as it respects the Requester type from @algolia/requester-common
.
BrowserXhrRequester
uses XMLHttpRequest.NodeHttpRequester
uses the native HTTP Node module.
1
2
3
4
5
6
7
8
9
10
import { createBrowserXhrRequester } from '@algolia/requester-browser-xhr';
import { createNodeHttpRequester } from '@algolia/requester-node-http';
const algoliasearch = algoliasearch(
'YourApplicationID',
'YourSearchOnlyAPIKey',
{
requester: createBrowserXhrRequester(), // or createNodeHttpRequester()
},
);
By default, requester
is set to:
algoliasearch/lite
(browser):BrowserXhrRequester
algoliasearch
(browser):BrowserXhrRequester
algoliasearch
(Node):NodeHttpRequester
Timeouts
Network and DNS resolution can be slow, which is why we have pre-configured timeouts. We don’t recommend changing them, but you can if you need to.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { createBrowserXhrRequester } from '@algolia/requester-browser-xhr';
import { createNodeHttpRequester } from '@algolia/requester-node-http';
const algoliasearch = algoliasearch(
'YourApplicationID',
'YourSearchOnlyAPIKey',
{
timeouts: {
connect: 1, // Timeout for the TCP session to connect.
read: 2, // Timeout for the read on the TCP socket.
write: 30, // Same as `read`, but only applies to write operations.
},
},
);
By default, timeouts
is set to:
algoliasearch/lite
(browser):{ connect: 1, read: 2, write: 30 }
algoliasearch
(browser):{ connect: 1, read: 2, write: 30 }
algoliasearch
(Node):{ connect: 2, read: 5, write: 30 }
User agent
Adding to the existing user agent
This option allows you to set a custom userAgent
while interacting with Algolia. This is useful when you are making an integration using algoliasearch
.
1
2
3
4
5
6
7
8
const searchClient = algoliasearch(
'YourApplicationID',
'YourSearchOnlyAPIKey'
);
searchClient.addAlgoliaAgent('CustomSegment', 'x.y.z');
// 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;
Replacing the default user agent
This option allows you to set a custom userAgent
while interacting with Algolia. This is useful when you are making a custom version of algoliasearch
for a different system than it supports by default. Note that this removes the existing “flavor” of the client, like Node.js or Browser.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// `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',
}),
},
);
// Algolia for JavaScript (a.b.c); CustomSegment (x.y.z);
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;
Headers and query parameters
The headers
and queryParameters
options let you add key/value pairs to your HTTP headers or query parameters.
1
2
3
4
5
6
7
8
9
10
11
12
const algoliasearch = algoliasearch(
'YourApplicationID',
'YourSearchOnlyAPIKey',
{
headers: {
'NAME-OF-HEADER': 'value-of-header',
},
queryParameters: {
'NAME-OF-QUERY-PARAMETER': 'value-of-query-parameter',
},
},
);
Using these options doesn’t override existing headers or query parameters with the new ones; it appends them.
Building the client from scratch
If you want complete control of your client, you can build it from scratch using the createSearchClient
function directly. This is what we use internally to build different algoliasearch
distributions, such as default
and lite
.
Please think twice before using createSearchClient
and make sure you need it, as you may not get automatic optimizations with new releases.
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 },
});
If you’re using a module bundler that supports ES modules, your client can benefit from tree shaking, keeping you from ending up with code you don’t need in production.