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
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_API_KEY=<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(),
});
}
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;
},
});
switch (result.type) {
case TopicSubscribeResponse.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();
break;
case TopicSubscribeResponse.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.
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.