Publishing Messages in Amazon SNS - Amazon SDK for JavaScript
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China (PDF).

We announced the upcoming end-of-support for Amazon SDK for JavaScript v2. We recommend that you migrate to Amazon SDK for JavaScript v3. For dates, additional details, and information on how to migrate, please refer to the linked announcement.

Publishing Messages in Amazon SNS

JavaScript code example that applies to Node.js execution

This Node.js code example shows:

  • How to publish messages to an Amazon SNS topic.

The Scenario

In this example, you use a series of Node.js modules to publish messages from Amazon SNS to topic endpoints, emails, or phone numbers. The Node.js modules use the SDK for JavaScript to send messages using this method of the AWS.SNS client class:

Prerequisite Tasks

To set up and run this example, you must first complete these tasks:

Publishing a Message to an Amazon SNS Topic

In this example, use a Node.js module to publish a message to an Amazon SNS topic. Create a Node.js module with the file name sns_publishtotopic.js. Configure the SDK as previously shown.

Create an object containing the parameters for publishing a message, including the message text and the ARN of the Amazon SNS topic. For details on available SMS attributes, see SetSMSAttributes.

Pass the parameters to the publish method of the AWS.SNS client class. Create a promise for invoking an Amazon SNS service object, passing the parameters object. Then handle the response in the promise callback.

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set region AWS.config.update({ region: "REGION" }); // Create publish parameters var params = { Message: "MESSAGE_TEXT" /* required */, TopicArn: "TOPIC_ARN", }; // Create promise and SNS service object var publishTextPromise = new AWS.SNS({ apiVersion: "2010-03-31" }) .publish(params) .promise(); // Handle promise's fulfilled/rejected states publishTextPromise .then(function (data) { console.log( `Message ${params.Message} sent to the topic ${params.TopicArn}` ); console.log("MessageID is " + data.MessageId); }) .catch(function (err) { console.error(err, err.stack); });

To run the example, type the following at the command line.

node sns_publishtotopic.js

This sample code can be found here on GitHub.