How to implement Amazon SNS email subscription on Gatsby website

Hello, I am a full stack developer since 2010 focused for a long moment more on backend stuffs. I embraced cloud development since 2019.
Search for a command to run...

Hello, I am a full stack developer since 2010 focused for a long moment more on backend stuffs. I embraced cloud development since 2019.
Hey fantastic Wilson! I will sure try this out. Congrats on the blog. I'm following!
Thank you Jose! Waiting for your suggestion if possible! Have a nice weekend!
Security in internet-facing or local applications is one of the most challenging parts of the software development life cycle. This post will provide a quick step-by-step guide to implementing access management for the previous REST API using Amazon ...

In this post, we will create a REST API endpoint with GET and POST methods for the previous backend using Amazon API Gateway's HTTP API. Prerequisites All you need is just an AWS account: no worries, if you are new to AWS, AWS offers you a 12-month f...

In this article, we'll build a simple CRUD JavaScript-based backend with AWS. We'll use Lambda and DynamoDB to show how you can quickly create a secure and robust app backend. Prerequisites To follow this tutorial, you need an AWS account. Thankfully...

There are many articles on how to build a real-world Spring Boot CRUD REST API or Application with MySQL as a Relational Database. In this post, we are not only going to show how to create a Spring Boot CRUD operations API, but we will also dive deep...

Before entering the AWS Cloud world, as a Java developer, it was often difficult for me to get Java-based applications online for my clients. Fortunately, I found out later that AWS provides many proven, fully managed services for deploying Java-bas...

I had difficulty implementing Amazon Simple Notification Service email subscription on one of my Gatsby websites. Yes you've read it well ๐, Gatsby , a React-based framework that helps you quickly build and deploy super fast lightweight websites.
In this post I will share, through a demo project, how you can easily implement this feature in your Gatsby website.




Now that we've created the sns subscription endpoint and the according user on AWS, we are going to setup our project.
Create a new project : gatsby new my-gatsby-project https://github.com/gatsbyjs/gatsby-starter-default
In the root of the project, type gatsby develop to run
Open the browser and type : http://localhost:8000

npm install -save aws-sdknpm install formik yupimport React from "react"
import { useFormik } from "formik"
import * as Yup from "yup"
export default function SubscribeForm() {
const formik = useFormik({
initialValues: {
email: "",
},
validationSchema: Yup.object({
email: Yup.string().email().required(),
}),
onSubmit(values, { resetForm }) {
const { email } = values
},
})
return (
<form onSubmit={formik.handleSubmit}>
<input
type="email"
name="email"
placeholder="Your email"
onChange={formik.handleChange}
value={formik.values.email}
/>
{formik.errors.email ? (
<span className="errorText">{formik.errors.email}</span>
) : null}
<input type="submit" value="Subscribe" />
</form>
)
}
import React from "react"
import { Link } from "gatsby"
import Layout from "../components/layout"
import Image from "../components/image"
import SEO from "../components/seo"
import SubscribeForm from "../components/subscribeform"
const IndexPage = () => (
<Layout>
<SEO title="Home" />
<h1>Hi people</h1>
<p>Welcome to your new Gatsby site.</p>
<p>Now go build something great.</p>
<div style={{ maxWidth: `300px`, marginBottom: `1.45rem` }}>
<Image />
</div>
<div style={{ maxWidth: `300px`, marginBottom: `1.45rem` }}>
<SubscribeForm />
</div>
<Link to="/page-2/">Go to page 2</Link> <br />
<Link to="/using-typescript/">Go to "Using TypeScript"</Link>
</Layout>
)
export default IndexPage

So far, everything works well as expected, but if you clic on subscribe button, nothing happens ๐คฃ, yes, because we haven't done anything so great, everbody who've gone through Gatsby tutorials could have done what we did! Let's add some codes to our subscribeform.js.
{
"accessKeyId": "secret",
"secretAccessKey": "secret",
"region": "secret"
}
Nota bene : You must replace "secret" with the corresponding accessKeyId , secretAccessKey and region values you've got in the Create a AWS programmatic user for aws-sdk section.
Warning : It is not a best practice to put app cridentials in a project, I'll have a post for how to do that, but for this subscription purpose, we'll not follow this best practice ๐คฆโโ๏ธ. Let's move on!
import AWS from "aws-sdk"
const AWSConf = require('../../config.json');
AWS.config.update(AWSConf);
var params = {
Protocol: "EMAIL" /* required */,
TopicArn: "yourArn" /* required */,
Endpoint: email,
}
var subscribePromise = new AWS.SNS({ apiVersion: "2010-03-31" })
.subscribe(params)
.promise()
subscribePromise
.then(function (data) {
resetForm() //reset the form
})
.catch(function (err) {
console.error(err, err.stack)
})
Nota bene : In the TopicArn: "yourArn" instruction, replace yourArn by the ARN generated through Configure Amazon SNS section. Voilร ! You've done the great thing ๐.
import React from "react"
import { useFormik } from "formik"
import * as Yup from "yup"
import AWS from "aws-sdk"
const AWSConf = require('../../config.json');
AWS.config.update(AWSConf);
export default function SubscribeForm() {
const formik = useFormik({
initialValues: {
email: "",
},
validationSchema: Yup.object({
email: Yup.string().email().required(),
}),
onSubmit(values, { resetForm }) {
const { email } = values
var params = {
Protocol: "EMAIL" /* required */,
TopicArn: "yourArn" /* required */,
Endpoint: email,
}
var subscribePromise = new AWS.SNS({ apiVersion: "2010-03-31" })
.subscribe(params)
.promise()
subscribePromise
.then(function (data) {
resetForm() //reset the form
})
.catch(function (err) {
console.error(err, err.stack)
})
},
})
return (
<form onSubmit={formik.handleSubmit}>
<input
type="email"
name="email"
placeholder="Your email"
onChange={formik.handleChange}
value={formik.values.email}
/>
{formik.errors.email ? (
<span className="errorText">{formik.errors.email}</span>
) : null}
<input type="submit" value="Subscribe" />
</form>
)
}

Well done! You have implemented an Amazon SNS email newsletter subscription in your Gatsby website.
You can find the source code here .