Skip to main content

Cheat Sheet for Node.js with Momento Cache

If you need to get going quickly with Node.js + TypeScript and Momento Cache, this page contains the basic API calls you'll need. Check the node.js SDK examples for complete, working examples including build configuration files.

Install the Momento client library

Install the client library in an existing node.js project:

npm install @gomomento/sdk

Set up your auth token

You'll need a Momento auth token to authenticate with Momento. You can get one from the Momento Web Console. Once you have your token, store it in an environment variable so that the Momento client can consume it:

export MOMENTO_AUTH_TOKEN=<your Momento token here>

Import libraries and connect to return a CacheClient object

This code sets up the main function, the necessary imports, and the CacheClient instantiation that each of the other functions will need to call.

/* eslint-disable @typescript-eslint/no-unused-vars */
import {CacheGet, CreateCache, CacheSet, CacheClient, Configurations, CredentialProvider} from '@gomomento/sdk';

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

try {
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('test-cache');
if (result instanceof CreateCache.Success) {
console.log("Cache 'test-cache' created");
} else if (result instanceof CreateCache.AlreadyExists) {
console.log("Cache 'test-cache' already exists");
} else if (result instanceof CreateCache.Error) {
throw new Error(
`An error occurred while attempting to create cache 'test-cache': ${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 it 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('test-cache', '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 'test-cache': ${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('test-cache', '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 'test-cache'");
} else if (result instanceof CacheGet.Error) {
throw new Error(
`An error occurred while attempting to get key 'test-key' from cache 'test-cache': ${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.