How to integrate dynamic functionality into static site. Contact form example from my blog.
I guess you have built a shiny new website using a static site generator like Jekyll, Hugo, Hexo, or similar, but you want more.
For example, you want your own form handling or other custom functionality. I will demonstrate how I built my contact form using AWS Lambda, SES, and API Gateway, and Serverless.js to do that. My plan is to use this approach to add a section with the most popular posts, and maybe to add a full content search. There are other ways to implement these, but I think this is the most cost effective.
You will need an Amazon Web Services account, and Node.js, NPM, and Serverless.js installed.
Install Serverless and create you projects
1 | npm install serverless -g |
You will need SU privileges to install serverless globally if you are using Linux.
If everything goes fine, you will have two files at your current working dir - handler.js, and serverless.yml.
Configure your new projects
I will paste my configuration. You will need to change your AWS user name, service name, roles, etc. - everything in square brackets.
1 | service: [service name] |
SES will throw errors if you don’t verify your domain and email address. Use this guide for SES email and domain verification.
Set up your AWS credentials
To give Serverless permission to create AWS services, you will need to set up an AWS user and grant him administrative permissions and configure serverless CLI with the users AWS key and secret.
I found this video very helpful.
Edit your AWS Lambda function
1 | ; |
Deploy to AWS
Deploy your project with the following command:1
serverless deploy
Save the function URL for later use to submit your form.
Form with AJAX call
Add the form to your website:
1 | <form class="contact-form"> |
Make sure to hide input with name “_sd” with CSS.
JavaScript code to submit the form:
1 | $('.contact-form').submit(function(evt) { |
AWS_URL should be changed with endpoint URL which is printed on successful deploy. You can always use “serverless info” command to get the URL.
You can test the function with cURL:
1 | curl 'https://ibmsxw1iq3.execute-api.us-east-1.amazonaws.com/dev/contact/send' -H 'origin: http://localhost:4000' -d'{"name":"Name","email":"you@yourmail.com","message":"test","_sd":""}' |
I would appreciate your suggestions, so please leave me a comment. My current concern is that someone who really hates me (thou I can’t think of anyone), trying to flood me with a huge number of emails. I would have to modify my function to do more security checks if that happens.