Page updated Feb 28, 2024

Cache

The Amplify Cache module provides a generic LRU cache for JavaScript developers to store data with priority and expiration settings.

It is a key/value structure where expiration values can be configured globally or on a per-key basis. For instance, you may wish to cache all JSON responses from the API module for the next 10 minutes, but like to store user input values or preferences for a month.

Installation

Install aws-amplify.

1npm install aws-amplify

Working with the API

First, import the library:

1import { Cache } from 'aws-amplify/utils';

After the import, you can invoke the appropriate methods within your application.

setItem()

1Cache.setItem(key, value, [options]);

You can set number, string, boolean, array or object values to the cache. You can also specify options along with the call such as the priority or expiration time.

1// Standard case
2Cache.setItem('key', 'value');
3
4// Set item with priority. Priority should be between 1 and 5.
5Cache.setItem('key', 'value', { priority: 3 });
6
7// Set item with an expiration time
8const expiration = new Date(2018, 1, 1);
9Cache.setItem('key', 'value', { expires: expiration.getTime() });

When using priority setting, the cached item with the higher number will be expired first. The Cache module decides expiration based on the memory available to the cache. In the following example,breakfastFoodOrder will be expired before mothersBirthday.

1Cache.setItem('mothersBirthday', 'July 18th', { priority: 1 });
2Cache.setItem('breakfastFoodOrder', 'Pancakes', { priority: 3 });

getItem()

1Cache.getItem(key[, options]);

Retrieves an item from the cache. It will return null if the item doesn’t exist or it has expired.

1// Standard case
2Cache.getItem('key');
3
4// Get item with callback function.
5// The callback function will be called if the item is not in the cache.
6// After the callback function returns, the value will be set into cache.
7Cache.getItem('key', { callback: callback });

removeItem()

Removes item from cache.

1Cache.removeItem(key);

clear()

Removes all of the items in the cache.

1Cache.clear();

getAllKeys()

Returns all of the keys available in the cache.

1Cache.getAllKeys();

getCacheCurSize()

Returns the current size of the cache in bytes.

1const size = Cache.getCacheCurSize();

configure()

Configures default settings for setItem functionality. You can see all available options in Configuration section.

1const config = {
2 itemMaxSize: 3000, // 3000 bytes
3 defaultPriority: 4
4 // ...
5};
6const myCacheConfig = Cache.configure(config);
7
8// You can modify parameters such as cache size, item default ttl and etc.
9// But don't try to modify keyPrefix which is the identifier of Cache.

createInstance()

Creates a new instance of Cache with custom configuration.

1const config = {
2 itemMaxSize: 3000, // 3000 bytes
3 storage: window.sessionStorage // switch to sessionStorage
4 // ...
5};
6const newCache = Cache.createInstance(config);
7// Please provide a new keyPrefix which is the identifier of Cache.

You can keep default values and only override the values you need as well.

1// Get default values
2const defaultConfig = Cache.configure();
3
4// Pass default config and overwrite only the options you want, ex: keyPrefix
5const customCache = Cache.createInstance({
6 ...defaultConfig,
7 keyPrefix: "my-custom-instance-prefix-",
8});

API Reference

For the complete API documentation for Cache module, visit our API Reference

Configuration

Configuration Parameters

Here is the list of configuration parameters for the Cache module:

ParameterTypeDescription
keyPrefixstringThe ID of Cache which can only be configured when creating new instance.
capacityInBytesnumberMax size of Cache in bytes. By default is 1MB and has a maximum of 5MB.
itemMaxSizenumberMax size of individual item which can be set into Cache in bytes. The default value is 200KB.
defaultTTLnumberTTL for the cache items in milliseconds. The default value is 72 hours.
defaultPrioritynumberDefault priority of the cache items. The default value is 5, the highest priority is 1.
warningThresholdnumberThis is for keeping Cache's current capacity in a reasonable level. The default is 0.8, which sets warnings for 80% of space usage.
storageStorageTypeThe storage medium that will be used for the Cache. Supported values are LocalStorage(default) and SessionStorage for Web development and AsyncStorage for React Native.

Configuration Parameters for Items

Here is the list of configuration parameters for the items in the cache :

ParameterTypeDescription
prioritynumberPriority of the item to be kept in cache. Higher priority means longer expiration time.
expiresnumberThe expiration time of the cache item in milliseconds.
callbackfunctionYou can provide a callback function with getItem() to implement cache miss scenarios. The provided function will only be called if there is not a match for the cache key, and the return value from the function will be assigned as the new value for the key in cache.