Skip to main content

Getting Started with Momento Storage 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 Storage. 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 StorageClient object

This code sets up the main function, pulls in the necessary imports, and instantiates the StorageClient that will be used to interact with your cache.

/* eslint-disable @typescript-eslint/no-unused-vars */
import {PreviewStorageClient, StorageConfigurations} from '@gomomento/sdk';

const storageClient = new PreviewStorageClient({
configuration: StorageConfigurations.Laptop.latest(),
});

Create a new store in Momento Storage

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

const result = await storageClient.createStore(storeName);
switch (result.type) {
case CreateStoreResponse.AlreadyExists:
console.log(`Store '${storeName}' already exists`);
break;
case CreateStoreResponse.Success:
console.log(`Store '${storeName}' created`);
break;
case CreateStoreResponse.Error:
throw new Error(
`An error occurred while attempting to create store '${storeName}': ${result.errorCode()}: ${result.toString()}`
);
}

List the names of existing stores in your account

A simple list of the names of stores for the account.

const result = await storageClient.listStores();
switch (result.type) {
case ListStoresResponse.Success:
console.log(
`Stores:\n${result
.stores()
.map(c => c.getName())
.join('\n')}\n\n`
);
break;
case ListStoresResponse.Error:
throw new Error(`An error occurred while attempting to list stores: ${result.errorCode()}: ${result.toString()}`);
}

Write an item to a store

A simple example of doing a put operation.

// to store a string value:
const result = await storageClient.putString(storeName, 'test-key', 'test-value');
switch (result.type) {
case StoragePutResponse.Success:
console.log("Key 'test-key' stored successfully");
break;
case StoragePutResponse.Error:
throw new Error(
`An error occurred while attempting to store key 'test-key' in store '${storeName}': ${result.errorCode()}: ${result.toString()}`
);
}

// Momento storage also supports these other data types:
await storageClient.putInt(storeName, 'test-key', 42);
await storageClient.putDouble(storeName, 'test-key', 3.14);
await storageClient.putBytes(storeName, 'test-key', Buffer.from('test-value'));

Read an item from a store

This is an example of a simple read operation to get an item from a store.

const getResponse = await storageClient.get(storeName, 'test-key');
// simplified style; assume the value was found, and that it was a string
console.log(`string hit: ${getResponse.value()!.string()!}`);

// if the value was an integer:
const integerGetResponse = await storageClient.get(storeName, 'test-integer-key');
console.log(`integer hit: ${integerGetResponse.value()!.int()!}`);

// pattern-matching style; safer for production code
switch (getResponse.type) {
case StorageGetResponse.Found:
// if you know the value is a string:
console.log(`Retrieved value for key 'test-key': ${getResponse.value().string()!}`);
break;
case StorageGetResponse.NotFound:
console.log(`Key 'test-key' was not found in store '${storeName}'`);
break;
case StorageGetResponse.Error:
throw new Error(
`An error occurred while attempting to get key 'test-key' from store '${storeName}': ${getResponse.errorCode()}: ${getResponse.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.