Introduction
Amazon SNS is a really useful component of the AWS ecosystem. It allows you to notify unlimited subscribers of events in what is known as a publish/subscribe pattern. A subscriber could be a web service, a mobile phone, an SQS queue or even an email address. In this quick code tip, I’ll show you how to install the AWS SDK and push an example notification to an SNS topic.
Requirements
You will need:
- An AWS account with permission to create and publish to SNS topics
- Good working knowledge of Node.js – specifically ES6, promises and self-invoking functions
- Node.js configured for your system
- The AWS CLI configured on your computer, you can follow my tutorial to get it set up on your Mac if you haven’t already!
Set up the Node.js project
Let’s make a new folder, and initialise it as a Node project:
$ mkdir ~/Projects/example-sns-publisher $ npm init
The program will ask you a few questions, you can safely choose the defaults. Now, we need to add the AWS SDK to the project:
$ npm install --save aws-sdk
Now we’re going to go over to our browser and create the SNS resource.
A note on regions
I was informed by a reader that I should talk a little bit about AWS Regions before we continue. Amazon has a presence in many countries and offers the opportunity to use a local endpoint for API operations, meaning that you benefit from lower latency.
When you configure the AWS CLI, by default the region is set to us-east-1
, which represents a data center in Oregon, US. This may or may not be desirable. For this tutorial, I will be using the region eu-west-1
, which is the closest datacenter to me. Where you see eu-west-1
highlighted in red, please substitute this for the region you’d like to use.
If you’d like to learn more about regions and regional endpoints, Amazon has a good article on this.
Create the SNS topic we will publish to
Ok great, let’s use the AWS CLI to create the SNS topic that we’ll use in our code:
$ aws sns create-topic --name cloudtutorials-example-topic --region eu-west-1
All being well you’ll get something that looks similar to this:
{ "ResponseMetadata": { "RequestId": "1469e8d7-1642-564e-b85d-a19b4b341f83" }, "TopicArn": "arn:aws:sns:us-west-2:0123456789012:cloudtutorials-example-topic" }
Copy the TopicArn
value, we’ll use that later. If you want to learn more about the create-topic command, click here.
Now, we need to create a subscription to test out our new event source.
Create a subscription for our events
We’re going to set up an email subscription, which will receive our events as they’re published. As I said before, this could be a web service or a queue eventually, but email means we can see the result instantly!
Enter the following command, substituting the TopicArn
we copied earlier, and your email address:
$ aws sns subscribe --region eu-west-1 --topic-arn arn:aws:sns:us-west-2:0123456789012:cloudtutorials-example-topic --protocol email --notification-endpoint my-email@example.com
Hit return to execute it. If all is well, we’ll see this:
{ "SubscriptionArn": "pending confirmation" }
The reason it says pending is that you need to confirm your e-mail address before continuing. This is basically an anti-spam measure on Amazon’s part.
You will shortly receive an email basically asking for you to click a button to confirm your subscription – do what it says!
If you don’t receive anything, double check your TopicArn
and email in the command above and run it again.
Send an event using code
Create a new file called app.js in your project folder. Let’s start off by adding the AWS SDK and a reference to our TopicArn
to the file:
const AWS = require('aws-sdk'); const SNS_TOPIC_ARN = ''; // Add your TopicArn that you got from the CLI command
We’re doing two things here. We require the aws-sdk
library into the file, and created a variable that holds our TopicArn
. We can now use both of these during the send.
Now, let’s scaffold out a basic function that tries to publish to SNS:
const AWS = require('aws-sdk'); const SNS_TOPIC_ARN = ''; // Get an instance of the SNS class which we can use here const sns = new AWS.SNS(); // Scaffold a self-executing async function (so we can use await!) (async () => { try { // Create the event object const publishParameters = { Message: 'Hello world!', TopicArn: SNS_TOPIC_ARN }; // Publish and wait using a promise const result = await sns.publish(publishParameters).promise(); // Log the result console.log(`Published to ${SNS_TOPIC_ARN}! ${result}`); } catch (error) { // Log any errors we get here. console.error(`Unable to publish to SNS: ${error.stack}`); } })();
Now. let’s run our app:
$ AWS_REGION=eu-west-1 node app.js
After a short delay, the terminal should return “Published to XXX” and (hopefully!) you will receive an email saying “Hello world!”. If so, you’ve successfully published to an SNS topic! AWESOME!
Please let me know in the comments if you had any trouble and I’ll do my best to help.