0

Introduction to AWS SNS using Nodejs

In this article, we will see what is AWS SNS and it’s usecases. also, we will see a real time example where we can use AWS SNS using Node.js. Introduction to AWS SNS using Nodejs

Recent Articles

How to Run MongoDB as a Docker Container in Development

Crafting multi-stage builds with Docker in Node.js

Learn MongoDB Aggregation with real world example

What is AWS SNS?

Amazon Simple Notification Service(SNS) is a web service that is used to manage the notifications for a web server,application,email and SMS.

Let’s try to understand this concept with an example, Let’s say you have a server instances running in AWS. you as a developer, wants to know when the server reaches the maximum CPU level.

At the same time, you don’t want to constantly check the server which is very time consuming. you can automate this process using AWS SNS.

Another example would be Sending Notification for you Application Crash in the server. you can use AWS SNS to send you the Crash log to you email, so that you can debug it in an efficient way.

AWS SNS Use-Cases

There are some use cases where SNS will be the right choice. we will see those use cases.

Fan-out/Pub-sub

Let’s take the previous scenario here. you want to get notified about your server health check in email, SMS and also to the other web server which uses this server.

In that case, AWS SNS will be right choice to go with.

Application System Alerts

When you want to get notified about your application status and usage metrics, you can use AWS SNS to do that.

Email and SMS Notification

Like it said before, email and SMS are the default medium that are provided by AWS SNS for notifications.

Push Notification

AWS SNS is also the best option for push notification for mobile and web applications.

AWS Setup for SNS

Mainly, the Usecase that we will take here is sending application status to email using AWS SNS.

Requirement for this article is to have an account in AWS. Once you create an Account, you need to generate credentials for accessing the AWS SNS.

To do that, you need to create an Identity Acess Management(IAM) for an user with AWS SNS Full Access.

Go to AWS Console -> IAM user -> create an user

After that, you need to add the user to group. Group is where we set the access for the service.

you can select the services that you want to give access to the users in the group.

Once you done with the process, you can be able to get the credentials for the user to access the services you specified.

Store the credentials in you machine to refer for the rest of the article.

Implementing AWS SNS in Nodejs Application

Firstly, create a boilerplate for express application and install the aws-sdk using the command,

npm init --yes
npm install --save express aws-sdk

Once, you installed the dependencies,we can start implementing the logic for our usecase.

AWS SNS works in the pattern of publisher/subscriber. create an app.js file and add the basic express application setup.

const express = require('express');
const app = express();

app.get('/', async (req, res) => {
    res.send("Welcome");
});


app.listen(3004, () => {
  console.log('Server is running in port 3004');
});

After that, add the aws setup in the application to access the SNS service.

const express = require('express');
const app = express();

const AWS_ACCESS_KEY_ID = '';
const AWS_SECRET_ACCESS_KEY = '';

AWS.config.update({
  region: 'us-east-2',
  accessKeyId: AWS_ACCESS_KEY_ID,
  secretAccessKey: AWS_SECRET_ACCESS_KEY
});

app.get('/', async (req, res) => {
    res.send("Welcome");
});

app.listen(3004, () => {
  console.log('Server is running in port 3004');
});

Logic that we are going to follow is when you hit the base url, we will check if the topic is already exists in the SNS, if not we will create it and returns the topicArn.

So, create a file called checkIfTopicExists.js to check if the topic exists or not,

module.exports = (AWS, topicName) => {
  return new Promise((resolve, reject) => {
    try {
      const listTopics = new AWS.SNS({ apiVersion: '2010-03-31' })
        .listTopics({})
        .promise();

      listTopics
        .then(data => {
          if (data.Topics.includes(topicName)) {
            resolve(true);
          } else {
            resolve(false);
          }
        })
        .catch(err => {
          throw err;
        });
    } catch (e) {
      reject(e);
    }
  });
};

Above code check if the topic is already exists in SNS service or not.

After that, create a file called createTopic.js that create a topic in SNS service.

module.exports = (AWS, topicName) => {
  return new Promise((resolve, reject) => {
    try {
      const createTopic = new AWS.SNS({ apiVersion: '2010-03-31' })
        .createTopic({
          Name: topicName
        })
        .promise();
      createTopic
        .then(data => {
          console.log(`Created Topic - ${topicName}`);
          console.log('data', data);
          resolve(data.TopicArn);
          //   topicARN = data.TopicArn;
        })
        .catch(err => {
          throw err;
        });
    } catch (e) {
      reject(e);
    }
  });
};

Once the topic is created, you need to subscribe to the topic using the email that you want to get notified.

create a subscription in AWS SNS console.

Once you create the email subscription, you will get an email to confirm the subscription.

That’s the setup for Email subscription for the topic.

finally, add those two files in the app.js to implement the logic.

const AWS = require('aws-sdk');

const AWS_ACCESS_KEY_ID = '';
const AWS_SECRET_ACCESS_KEY = '';
let topicARN = '';
AWS.config.update({
  region: 'us-east-2',
  accessKeyId: AWS_ACCESS_KEY_ID,
  secretAccessKey: AWS_SECRET_ACCESS_KEY
});

const express = require('express');

const checkIfTopicExists = require('./checkIfTopicExists');
const createTopic = require('./createTopic');
const publishToTopic = require('./publishToTopic');

const app = express();

app.get('/', async (req, res) => {
  const ifTopicExists = await checkIfTopicExists(AWS, 'ON_POST_CREATED');

  if (!ifTopicExists) {
    let topicARN = await createTopic(AWS, 'ON_POST_CREATED');
    topicARN = topicARN;
    res.send(topicARN);
  } else {
    res.send(ifTopicExists);
  }
});

app.get('/publish', async (req, res) => {
  const ifTopicExists = await checkIfTopicExists(AWS, 'ON_POST_CREATED');

  if (!ifTopicExists) {
    await publishToTopic(
      AWS,
      'arn:aws:sns:us-east-2:602909638965:ON_POST_CREATED',
      'Hello World'
    );
  }
});

app.listen(3004, () => {
  console.log('Server is running in port 3004');
});

Once you have done that, it is time to test the code. run the code using node app.js

you can see the output like

it shows that the message sent successfully, which means you should get a mail with a message like this,

Recommended Course

There are some wonderful courses to learn AWS Concepts. i recommend you to get this awesome course

ganeshmani009

Leave a Reply

Your e-mail address will not be published. Required fields are marked *