Skip to main content

Cheat sheet for Node.js with Momento Topics

If you need to get going quickly with Node.js + TypeScript and Momento Topics, 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 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('test-cache', 'test-topic', {
onError: () => {
return;
},
onItem: (item: TopicItem) => {
console.log(`Publishing values to the topic 'test-topic': ${item.value().toString()}`);
return;
},
});
if (result instanceof TopicSubscribe.Subscription) {
console.log("Successfully subscribed to topic 'test-topic'");

// Publish a value
await topicClient.publish('test-cache', 'test-topic', 'test-value');

// Wait for published values to be received.
setTimeout(() => {
console.log('Waiting for the published values');
}, 2000);

// 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 '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.