Skip to main content

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
tip

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 {CacheGet, CreateCache, CacheSet, CacheClient, Configurations, CredentialProvider} from '@gomomento/sdk';

async function main() {
const cacheClient = await CacheClient.create({
configuration: Configurations.Laptop.v1(),
credentialProvider: CredentialProvider.fromEnvironmentVariable({
environmentVariableName: 'MOMENTO_API_KEY',
}),
defaultTtlSeconds: 60,
});
}

main().catch(e => {
console.error(`Uncaught exception while running example: ${JSON.stringify(e)}`);
throw e; // Depending on the environment, this might not be necessary.
});

Create a new cache in Momento Cache

Use this function to create a new cache in your account.

const result = await cacheClient.createCache(cacheName);
if (result instanceof CreateCache.Success) {
console.log(`Cache '${cacheName}' created`);
} else if (result instanceof CreateCache.AlreadyExists) {
console.log(`Cache '${cacheName}' already exists`);
} else if (result instanceof CreateCache.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();
if (result instanceof ListCaches.Success) {
console.log(
`Caches:\n${result
.getCaches()
.map(c => c.getName())
.join('\n')}\n\n`
);
} else if (result instanceof ListCaches.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');
if (result instanceof CacheSet.Success) {
console.log("Key 'test-key' stored successfully");
} else if (result instanceof CacheSet.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 result = await cacheClient.get(cacheName, 'test-key');
if (result instanceof CacheGet.Hit) {
console.log(`Retrieved value for key 'test-key': ${result.valueString()}`);
} else if (result instanceof CacheGet.Miss) {
console.log(`Key 'test-key' was not found in cache '${cacheName}'`);
} else if (result instanceof CacheGet.Error) {
throw new Error(
`An error occurred while attempting to get key 'test-key' from cache '${cacheName}': ${result.errorCode()}: ${result.toString()}`
);
}

Running the code

You can find complete, working examples in the JavaScript SDK GitHub repo examples directory.

info

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.