Latest news about Bitcoin and all cryptocurrencies. Your daily crypto news habit.
What if I told you it can be done with zero dependencies? Hope youâre up for a challenge because thatâs exactly what weâll be doing.
This tutorial will cover the basics of both the front-end contact form, with vanilla JavaScript, and the serverless back end hosted on AWS Lambda. AWS SES is the service you use for sending the actual emails and trust me, itâs so incredibly simple the configuration takes 13 seconds. Yes, I timed myself. đ
Well, okay then. Letâs jump in!
TL;DR
Just to make sure you have an overview of what weâre doing today, hereâs a short TL;DR. You can jump to the section that interests you, and severely hurt my feelings, or just keep reading from here. Take your pick⊠I wonât silently judge you. đ
- What are we building?
- Configure AWSÂ SES
- Build the API with the Serverless Framework
- Deploy the API to AWSÂ Lambda
- Test the API with Dashbird
- Build the form
Note: I turned this code into an npm module for easier re-usability, and so you peeps donât need to write all the code yourself when you need a quick contact form.
What are we building?
The general idea is to build a contact form that can be added to a static website. We want to add it without managing any servers and ideally not paying anything for it to run. Hereâs an amazing use case for AWSÂ Lambda.
The structure of what we want to build is rather simple. We have a simple form, with a tiny snippet of JavaScript to parse the parameters to JSON and send them to an API endpoint.
The endpoint is an AWS API Gateway event, which will trigger an AWS Lambda function. The function will tell AWS SES to send an email with the content to your email address. From there you can continue exchanging emails with the person who filled out the form. Simple, right?
Letâs start hacking!
Configure AWSÂ SES
In order to send emails with the Simple Email Service AWS provides, you need to verify an email address which will be used to send the emails. Itâs as simple as navigating to the AWS Console and searching for Simple Email Service.
Once there press the Email Addresses link on the left side navigation. Youâll see a big blue button called Verify a New Email Address. Press it and add your email address.
AWS will now send you a verification email to that address. Go ahead and verify it. Thatâs pretty much it. Ready to write some code now?
Build the API with the Serverless Framework
There are a couple of main steps in building the actual API. First thing, as always, is the configuration.
1. Install the Serverless Framework
In order for serverless development to not be absolute torture, go ahead and install the Serverless framework.
$ npm i -g serverless
Note: If youâre using Linux, you may need to run the command as sudo.
Once installed globally on your machine, the commands will be available to you from wherever in the terminal. But for it to communicate with your AWS account you need to configure an IAM User. Jump over here for the explanation, then come back and run the command below, with the provided keys.
$ serverless config credentials \ --provider aws \ --key xxxxxxxxxxxxxx \ --secret xxxxxxxxxxxxxx
Now your Serverless installation knows what account to connect to when you run any terminal command. Letâs jump in and see it in action.
2. Create a service
Create a new directory to house your Serverless application services. Fire up a terminal in there. Now youâre ready to create a new service.
Whatâs a service you ask? View it like a project. But not really. Itâs where you define AWS Lambda functions, the events that trigger them and any AWS infrastructure resources they require, all in a file called serverless.yml.
Back in your terminal type:
$ serverless create --template aws-nodejs --path contact-form-api
The create command will create a new service. Shocker! But hereâs the fun part. We need to pick a runtime for the function. This is called the template. Passing in aws-nodejs will set the runtime to Node.js. Just what we want. The path will create a folder for the service.
3. Explore the service directory with a code editor
Open up the contact-form-api folder with your favorite code editor. There should be three files in there, but for now, weâll only focus on the serverless.yml. It contains all the configuration settings for this service. Here you specify both general configuration settings and per function settings. Your serverless.yml will be full of boilerplate code and comments. Feel free to delete it all and paste this in.
The functions property lists all the functions in the service. We will only need one function though, to handle the sending of emails. The handler references which function it is.
Take a look at the iamRoleStatements, they specify the Lambda has permission to trigger the Simple Email Service.
We also have a custom section at the top. This acts as a way to safely load environment variables into our service. They're later referenced by using ${self:custom.secrets.<environment_var>} where the actual values are kept in a simple file called secrets.json.
Awesome!
4. Add the secrets file
We all know pushing private keys to GitHub kills little puppies. Please donât do that. Handling this with the Serverless Framework is simple. Add a secrets.json file and paste these values in.
While testing you can keep the domain as '*', however, make sure to change this to your actual domain in production. The EMAIL field should contain the email you verified with AWSÂ SES.
5. Write business logic
With that wrapped up, letâs write the actual code. All in all, the code itself is rather simple. Weâre requiring the SES module, creating the email parameters and sending them with the .sendMail() method. At the bottom, we're exporting the function, making sure to make it available in the serverless.yml.
Thatâs it, all about 60 lines of code, with absolutely no dependencies. Sweet!
Deploy the API to AWSÂ Lambda
Here comes the easy part. Deploying the API is as simple as running one command.
$ serverless deploy
You can see the endpoint get logged to the console. Thatâs where you will be sending your requests.
Test the API with Dashbird
The simplest way of testing an API is with CURL. Letâs create a simple CURL command and send a JSON payload to our endpoint.
$ curl --header "Content-Type: application/json" \ --request POST \ --data '{"email":"john.doe@email.com","name":"John Doe","content":"Hey!"}' \ https://{id}.execute-api.{region}.amazonaws.com/{stage}/email/send
If everything works like it should, you will get an email shortly. If not, well then youâre out of luck. In cases like these, I default to using Dashbird to debug whatâs going on.
The logs on my end are showing all green, so itâs working perfectly! Thatâs the API part done. Letâs move on to the contact form itself.
Build the contact form
Because Iâm not the best CSS guru in the world, Iâll just entirely skip that part and show you how to make it work. đ
Letâs start with the HTMLÂ markup.
Itâs an incredibly simple form with three fields and a button. Letâs move on to the JavaScript.
Another 50 lines and you have the client side logic done. Feel free to drop this into your website, change the url constant to the API endpoint you deployed above. Hey presto, there's your serverless contact form done and ready for production!
Wrapping up
There you have it, a quick and easy way to add a serverless contact form to a website. Using serverless for the odd, isolated endpoint like this is great. There are absolutely no servers you need to worry about. Just deploy the code and rest assured itâll work. If something breaks, you have Dashbird watching your back, alerting you in Slack if something is wrong. Damn, I love Slack integrations.
Anyhow, I took the time to create an npm module out of the code above, so in the future, nobody needs to write this twice. Just install the package and thereâs your contact form endpoint up and running in less than a minute. You can find the instructions in the GitHub repo, if you want to take a look. Give it a star if you want more people to see it on GitHub.
If you want to read some of my previous serverless musings head over to my profile or join my newsletter!
Or, take a look at a few of my articles right away:
- A crash course on Serverless APIs with Express and MongoDB
- Solving invisible scaling issues with Serverless and MongoDB
- How to deploy a Node.js application to AWS Lambda using Serverless
- Getting started with AWS Lambda and Node.js
- A crash course on securing Serverless APIs with JSON web tokens
- Migrating your Node.js REST API to Serverless
- Building a Serverless REST API with Node.js and MongoDB
- A crash course on Serverless with Node.js
Hope you guys and girls enjoyed reading this as much as I enjoyed writing it. If you liked it, slap that tiny clap so more people here on Medium will see this tutorial. Until next time, be curious and have fun.
Originally published at dev.to.
Building a serverless contact form with AWS Lambda and AWS SES was originally published in Hacker Noon on Medium, where people are continuing the conversation by highlighting and responding to this story.
Disclaimer
The views and opinions expressed in this article are solely those of the authors and do not reflect the views of Bitcoin Insider. Every investment and trading move involves risk - this is especially true for cryptocurrencies given their volatility. We strongly advise our readers to conduct their own research when making a decision.