
This assumes you are familar with the basic configurations needed to connect to Amazon Web Services (AWS) using NodeJS. If not, check out my article Getting Started with NodeJS aws-sdk.
The @aws-sdk/client-sns package is used to interact with AWS Simple Notification Service (SNS) in NodeJS. The npm list command can be used to determine if you have the @aws-sdk/client-sns package installed. If not, the npm install command can be used to install the @aws-sdk/client-sns package. Once installed, your package.json should include the @aws-sdk/client-sns package.
{
"dependencies": {
"@aws-sdk/client-sns": "^3.600.0"
}
}
Here is the minimal boilerplate code without any error handling to publish a message to one of your SNS Topics using NodeJS CommonJS.
const { SNSClient, PublishCommand } = require("@aws-sdk/client-sns");
const client = new SNSClient({ region: "us-east-1" });
client.send(new PublishCommand({Subject: "Hello", Message: "Hello World",TopicArn: "arn:aws:sns:us-east-1:123456789012:my-topic"}));
If your app is an ES module, package.json will have "type": "module".
{
"type":"module",
"dependencies": {
"@aws-sdk/client-sns": "^3.620.0"
}
}
In this scenario, you will use import instead of require.
import { SNSClient, PublishCommand } from "@aws-sdk/client-sns";
Often, the parameters and command are defined as variables or constants.
const { SNSClient, PublishCommand } = require("@aws-sdk/client-sns");
const client = new SNSClient({ region: "us-east-1" });
const params = {
Subject: "Hello",
Message: "Hello World",
TopicArn: "arn:aws:sns:us-east-1:123456789012:my-topic"
};
const command = new PublishCommand(params);
client.send(command);
Often, this is put in an async function.
const { SNSClient, PublishCommand } = require("@aws-sdk/client-sns");
const client = new SNSClient({ region: "us-east-1" });
async function publishMessage(arn, subject, message) {
const params = {
Subject: subject,
Message: message,
TopicArn: arn
};
const command = new PublishCommand(params);
return await client.send(command);
}
publishMessage("arn:aws:sns:us-east-1:123456789012:my-topic", "Hello", "World")
.then(response => {console.log(response)})
.catch(err => {console.error(err)});
If the message is successfully published, something like this should be returned.
{
'$metadata': {
httpStatusCode: 200,
requestId: '073ac063-adbd-5448-ad8e-9f43aec496a9',
extendedRequestId: undefined,
cfId: undefined,
attempts: 1,
totalRetryDelay: 0
},
MessageId: 'cfb3d9ea-2f1a-530f-ba31-86ca2c6371ee'
}
Did you find this article helpful?
If so, consider buying me a coffee over at