Skip to main content

Introduction to AWS SNS using Nodejs

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

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

iam iser 1

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.

iam user success

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,

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

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

aws sns Page 2

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

1const express = require("express")
2const app = express()
3
4app.get("/", async (req, res) => {
5 res.send("Welcome")
6})
7
8app.listen(3004, () => {
9 console.log("Server is running in port 3004")
10})

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

1const express = require("express")
2const app = express()
3
4const AWS_ACCESS_KEY_ID = ""
5const AWS_SECRET_ACCESS_KEY = ""
6
7AWS.config.update({
8 region: "us-east-2",
9 accessKeyId: AWS_ACCESS_KEY_ID,
10 secretAccessKey: AWS_SECRET_ACCESS_KEY,
11})
12
13app.get("/", async (req, res) => {
14 res.send("Welcome")
15})
16
17app.listen(3004, () => {
18 console.log("Server is running in port 3004")
19})

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,

1module.exports = (AWS, topicName) => {
2 return new Promise((resolve, reject) => {
3 try {
4 const listTopics = new AWS.SNS({ apiVersion: "2010-03-31" })
5 .listTopics({})
6 .promise()
7
8 listTopics
9 .then(data => {
10 if (data.Topics.includes(topicName)) {
11 resolve(true)
12 } else {
13 resolve(false)
14 }
15 })
16 .catch(err => {
17 throw err
18 })
19 } catch (e) {
20 reject(e)
21 }
22 })
23}

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.

1module.exports = (AWS, topicName) => {
2 return new Promise((resolve, reject) => {
3 try {
4 const createTopic = new AWS.SNS({ apiVersion: "2010-03-31" })
5 .createTopic({
6 Name: topicName,
7 })
8 .promise()
9 createTopic
10 .then(data => {
11 console.log(`Created Topic - ${topicName}`)
12 console.log("data", data)
13 resolve(data.TopicArn)
14 // topicARN = data.TopicArn;
15 })
16 .catch(err => {
17 throw err
18 })
19 } catch (e) {
20 reject(e)
21 }
22 })
23}

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.

create subscription

console subscription

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

subscription confirmation

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

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

1const AWS = require("aws-sdk")
2
3const AWS_ACCESS_KEY_ID = ""
4const AWS_SECRET_ACCESS_KEY = ""
5let topicARN = ""
6AWS.config.update({
7 region: "us-east-2",
8 accessKeyId: AWS_ACCESS_KEY_ID,
9 secretAccessKey: AWS_SECRET_ACCESS_KEY,
10})
11
12const express = require("express")
13
14const checkIfTopicExists = require("./checkIfTopicExists")
15const createTopic = require("./createTopic")
16const publishToTopic = require("./publishToTopic")
17
18const app = express()
19
20app.get("/", async (req, res) => {
21 const ifTopicExists = await checkIfTopicExists(AWS, "ON_POST_CREATED")
22
23 if (!ifTopicExists) {
24 let topicARN = await createTopic(AWS, "ON_POST_CREATED")
25 topicARN = topicARN
26 res.send(topicARN)
27 } else {
28 res.send(ifTopicExists)
29 }
30})
31
32app.get("/publish", async (req, res) => {
33 const ifTopicExists = await checkIfTopicExists(AWS, "ON_POST_CREATED")
34
35 if (!ifTopicExists) {
36 await publishToTopic(
37 AWS,
38 "arn:aws:sns:us-east-2:602909638965:ON_POST_CREATED",
39 "Hello World"
40 )
41 }
42})
43
44app.listen(3004, () => {
45 console.log("Server is running in port 3004")
46})

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

demo

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

notification

Recommended Course

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

Comments

Popular posts from this blog

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...