Caching
The API client caches requests to Algolia, the corresponding responses, and the list of hosts it has already contacted. You can change the location of your caches, or turn off caching completely.
Find the implementation of the following Algolia-provided caching mechanism in @algolia/client-common
:
null
: to turn off caching.in memory
: everything is stored in memory. It’s cleared when the page is refreshed.local storage
: the API client uses the browser’s local storage. It’s cleared when the browser’s cache duration (TTL) expires.fallbackable
: conditionally selects one of the other cache types.
Requests and responses
If the same query is performed again during a search session, the API 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 API client retrieves results from the response cache for queries that have already been performed during a search session.
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. This helps avoid unreachable hosts.
Default implementations
These are the default caching mechanisms used per environment:
Browser | Node | Workers | |
---|---|---|---|
Requests | in memory |
null |
null |
Responses | in memory |
null |
null |
Hosts | local storage with fallback to in memory |
in memory |
in memory |
Custom implementations
You can use a different caching solution when initializing the client.
For example, use the Algolia-provided implementations from @algolia/client-common
:
1
2
3
4
5
6
7
8
9
10
11
import { algoliasearch } from 'algoliasearch';
import { createNullCache, createBrowserLocalStorageCache, createMemoryCache, createFallbackableCache } from '@algolia/client-common';
const client = algoliasearch("YOUR_APP_ID", "YOUR_API_KEY", {
requestsCache: createBrowserLocalStorageCache({ key: 'my-local-storage-key' }), // local storage is only available in the browser environment
responsesCache: createFallbackableCache({ caches: [ // fallbackable cache will try each caching mechanism in the given order
createMemoryCache(),
createNullCache(), // null cache is a no-op
] }),
hostsCache: createMemoryCache(),
});
Alternatively, you can implement a custom caching solution that follows the guidelines outlined in this cache
interface definition.
Clear caches
The API client exposes an asynchronous clearCache
method that calls the clear
method of the requests
and responses
caches.
1
2
3
4
5
6
7
import { algoliasearch } from 'algoliasearch';
const client = algoliasearch("YOUR_APP_ID", "YOUR_API_KEY");
// .... Do some operations
await client.clearCache();