How to make Serverless contact form
As a developer, I often need to run a set of several tasks happened when certain event occurs. For example:
- Send a few emails when form is submitted;
- Send a message to the Slack channel when incoming webhook received (e.g. when new order placed in Shopify);
- Make an API request when form is submitted (e.g. Newsletter subscription form).
Definitely, this is not an issue when all this functionality can be added to the core functionality of the app/or website. However, in some cases, it's not possible to extend core functionality of the app, and making another standalone application just to handle contact form does not make sense (especially, if your client needs a cost-effective solution and our time is limited).
Let's say, we have a client who have a static HTML website, and wanted to add a simple contact form, which just sends an email when someone submits the form.
Of course, there are number of services, like Formspree, which we can use for this task. However, functionality of such services is limited, so if later our client want to receive notifications to the Slack channel, we'll need to find a way to connect this service with Slack.
So, how we can solve this issue and offer cost-effective and easy to use solution to our customer? The answer is - use serverless approach! Serverless functions are great for such tasks, as they provide the following benefits:
- They're easy to use and customize;
- No need to worry about hosting and other technical questions;
- Low operating costs (for small projects, serverless functions could be run at no cost at all);
- They could be easily re-used in other projects;
- As we own the code, we can customize functionality as needed;
As an example, I wrote simple function which could be hosted on Cloudflare Workers. That function will listen for incoming
POST request, validates incoming form data, and if everything is correct, sends an email to website admin and email confirmation to the sender:
You can also take a look a t live demo on Sandbox.
A few notes:
- Tried to keep worker's source code as simple as possbile, with no dependencies, so the function could be deployed using Cloudflare Web UI.
- It's a good idea to add some anti-spam/honeypot protection mechanism, that's why we named email field name as
eml, and added another not visible
eml2email field (if that field isn't empty, then most likely our form has been filled-in by spam-bot);
- In the example above, emails are sent via Mailgun API, feel free to use any other service for this task;
This function could be hosted on any other serverless service provider, for example - AWS Lambda. However, in my opinion, Cloudflare Workers - is a great service to host small serverless functions, while AWS Lambda requires more initial setup and configuration.