Skip to main content

Getting Started with Momento Topics 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 Topics. 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, preferably a fine-grained token, from the Momento Web Console. Once you have a token, store it in an environment variable so that the Momento client can consume it:

export MOMENTO_AUTH_TOKEN=<your Momento token here>

Note: it is best practice to put the token 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 TopicClient object

This code sets up the main function, pulls in the necessary imports, and instantiates the TopicClient that will be used to interact with your pub/sub topic.

/* eslint-disable @typescript-eslint/no-unused-vars */
import {TopicClient, TopicConfigurations, CredentialProvider} from '@gomomento/sdk';

function main() {
const cacheClient = new TopicClient({
configuration: TopicConfigurations.Default.latest(),
credentialProvider: CredentialProvider.fromEnvironmentVariable({
environmentVariableName: 'MOMENTO_API_KEY',
}),
});
}

try {
main();
} catch (e) {
console.error(`Uncaught exception while running example: ${JSON.stringify(e)}`);
throw e;
}

Subscribe and publish a message to a topic

This example subscribes to a topic called "test-topic" in the Momento Cache named "test-cache", then it publishes to the topic if the subscription is successful.

const result = await topicClient.subscribe(cacheName, 'test-topic', {
onError: () => {
return;
},
onItem: (item: TopicItem) => {
console.log(`Received an item on subscription for 'test-topic': ${item.value().toString()}`);
return;
},
});
if (result instanceof TopicSubscribe.Subscription) {
console.log("Successfully subscribed to topic 'test-topic'");

console.log("Publishing a value to the topic 'test-topic'");
// Publish a value
await topicClient.publish(cacheName, 'test-topic', 'test-value');

console.log('Waiting for the published value to be received.');
await new Promise(resolve => setTimeout(resolve, 1000));

// Need to close the stream before the example ends or else the example will hang.
result.unsubscribe();
} else if (result instanceof TopicSubscribe.Error) {
throw new Error(
`An error occurred while attempting to subscribe to the topic 'test-topic' in 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.