Getting Started with Momento Cache in JavaScript
Momento provides two JavaScript SDKs; one for Node.js and one for browsers other web applications. The two SDKs have identical APIs, so your code will look the same except for import
statements, but under the hood they are built for optimal performance and compatibility in different JavaScript runtime environments.
This page contains the basics that you will need in order to get going quickly with Momento Cache. For more in-depth information and examples, visit the SDK pages linked above.
Install the Momento SDK
To Install the Momento Node.js SDK in an existing Node.js project:
npm install @gomomento/sdk
OR, to install the Momento Web SDK in an existing browser application project:
npm install @gomomento/sdk-web
You only need one of the two libraries; either @gomomento/sdk
or @gomomento/sdk-web
, depending on your target platform. You do not need both.
Set up your API key
You'll need a Momento API key to authenticate with Momento. You can get one from the Momento Web Console. Once you have your API key, store it in an environment variable so that the Momento client can consume it:
export MOMENTO_API_KEY=<your Momento API key here>
Note: it is best practice to put the API key into something like AWS Secret Manager or GCP Secret Manager instead of an environment variable for enhanced security, but we are using one here for demo purposes.
Import libraries and create a CacheClient object
This code sets up the main function, pulls in the necessary imports, and instantiates the CacheClient that will be used to interact with your cache.
/* eslint-disable @typescript-eslint/no-unused-vars */
import {CacheClient} from '@gomomento/sdk';
async function main() {
const cacheClient = await CacheClient.create({
defaultTtlSeconds: 60,
});
}
main().catch(e => {
console.error(`Uncaught exception while running example: ${JSON.stringify(e)}`);
throw e;
});
Create a new cache in Momento Cache
Use this function to create a new cache in your account.
const result = await cacheClient.createCache(cacheName);
switch (result.type) {
case CreateCacheResponse.AlreadyExists:
console.log(`Cache '${cacheName}' already exists`);
break;
case CreateCacheResponse.Success:
console.log(`Cache '${cacheName}' created`);
break;
case CreateCacheResponse.Error:
throw new Error(
`An error occurred while attempting to create cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}
List the names of existing caches in your account
A simple list of the names of caches for the account.
const result = await cacheClient.listCaches();
switch (result.type) {
case ListCachesResponse.Success:
console.log(
`Caches:\n${result
.getCaches()
.map(c => c.getName())
.join('\n')}\n\n`
);
break;
case ListCachesResponse.Error:
throw new Error(`An error occurred while attempting to list caches: ${result.errorCode()}: ${result.toString()}`);
}
Write an item to a cache
A simple example of doing a set operation. In the client.set call, the TTL is optional. If you did pass it in, this would override the default TTL value set with the client connection object.
const result = await cacheClient.set(cacheName, 'test-key', 'test-value');
switch (result.type) {
case CacheSetResponse.Success:
console.log("Key 'test-key' stored successfully");
break;
case CacheSetResponse.Error:
throw new Error(
`An error occurred while attempting to store key 'test-key' in cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}
Read an item from a cache
This is an example of a simple read operation to get an item from a cache.
const getResponse = await cacheClient.get(cacheName, 'test-key');
// simplified style; assume the value was found
console.log(`cache hit: ${getResponse.value()!}`);
// pattern-matching style; safer for production code
switch (getResponse.type) {
case CacheGetResponse.Hit:
console.log(`Retrieved value for key 'test-key': ${getResponse.valueString()}`);
break;
case CacheGetResponse.Miss:
console.log(`Key 'test-key' was not found in cache '${cacheName}'`);
break;
case CacheGetResponse.Error:
throw new Error(
`An error occurred while attempting to get key 'test-key' from cache '${cacheName}': ${getResponse.errorCode()}: ${getResponse.toString()}`
);
}
Running the code
You can find complete, working examples in the JavaScript SDK GitHub repo examples directory.
Beyond these basic API calls check out the API reference page for more information on the full assortment of Momento API calls.
Follow this link to see this same type of code but for more advanced calls.