AWS SDK for JavaScript
Developer Guide for SDK v2

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 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 SNS topic. For details on available SMS attributes, see SetSMSAttributes in the Amazon Simple Notification Service API Reference of the SNS topic.

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} send 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.