Implementing a form with SendGrid + microCMS


The cost of building a form
<p>When it comes to building form functionality the traditional way, there are quite a few specifications you need to think through. Of course you need a web server and a mail server, and if you want to store the submitted data, you also need a database.<br>Once you factor in the cost of building and maintaining all of that, plus the security concerns, the bar can feel pretty high. Many of you have probably felt the same way.<br>In this article, with “serverless” as our theme, we’ll walk through how to implement a low-cost form using the cloud-based email delivery service “SendGrid” and the headless CMS “microCMS.”</p>
What is SendGrid?
SendGrid is a cloud-based email delivery service.<br>You don’t need to build a mail server—just create an account, and you can start sending email the same day. That kind of simplicity is its biggest strength.
It’s also free for up to 12,000 emails per month, so getting started is wonderfully low-friction.
Their Web API is well-documented, and there are plenty of tutorials to help you integrate it with your own systems.
What is microCMS?
microCMS is one of the few headless CMS platforms made in Japan. Because it’s hosted in the cloud, there’s no server management to worry about.
If you’re wondering what a headless CMS even is, take a look at this article.
“10 Trending Headless CMS Platforms in 2021” (Japanese)
microCMS’s biggest strength is that it’s built and supported in Japan. You can ask questions through the chat in the admin panel and get responsive, attentive replies in Japanese—a real reassurance for developers based here.
The official blog is also thorough and well-written, so development tends to move along smoothly. The entry-level plan is free.
In this article, we’re going to use microCMS as a database to store form submissions. Hopefully it gives you a sense of what you can do with its POST functionality beyond the typical use case.
Overview of the architecture
Before we get into the actual implementation steps, let’s look at the overall architecture.
When the user clicks the submit button on the contact form, that single click triggers two events:
① An automated reply email (handled by SendGrid)
② Storing the submitted data (handled by microCMS)


Once you have the big picture, let’s start building.
Creating an Email Template in SendGrid
We’ll use SendGrid’s Dynamic Transactional Templates to create the auto-reply email that gets sent after the form is submitted.
For how to create a Dynamic Transactional Template:
SendGrid Official Tutorial
SendGrid Authorized Reseller Tutorial (Japanese)
Once you create a new template, choose [Build] > [Text] and drag it into [Drag Module Here].
You can type directly inside the TEXT block you just dragged in, so go ahead and write the body of your email. To insert form input values, wrap the ID in {{ }} as a template tag.
For this article, we’ll register the IDs using the following naming convention:
Name: name
Email address: mail
Message: text
You can verify your template tags using test data.
Click [PREVIEW] > [Show Test Data] to open the editor and enter your test values. The test data is reflected in the email preview on the right in real time, so you can see exactly how the finished email will look.
Finally, click [Save] to save your template.
Make a note of the Template ID shown on the Dynamic Templates list page—you’ll need it later.
You’ll also need an API Key to connect from the web side. Create one from the admin panel via [Settings] > [API Keys] > [Create API Key].
Creating an API to Store the Data
Now we’ll create an API in microCMS to store the form submission data.
The official microCMS blog article “Getting Started with microCMS” (Japanese) walks through API creation clearly, so use that as your reference.
Use names that are easy to recognize for both the API name and the endpoint. For this article, we used “Contact” and “contact” respectively. Choose “List Format” for the API type.
Next, define the API schema.
We’ll use the same field IDs as we did in SendGrid:
Name: name
Email address: mail
Message: text
We set up name and email address as text fields, and the message as a text area.
Since we want a POST request to be sent when the form is submitted, we need to configure the HTTP methods. By default only GET is enabled, so head into the settings below and enable POST as well.
[API Settings] > [HTTP Methods]
* This API is purely for storing POST data, so you don’t need to register any content yourself.
That’s it for the API setup.
Finally, open [Contact] > [API Preview] and make a note of the X-WRITE-API-KEY for POST requests.
Building the Form UI
For this article, we built the contact form using Next.js + Vercel, which produced the screen below. As long as your stack can call an API, feel free to use whatever platform you prefer.


When the user clicks the [Submit] button, we want the following code to run.
axios.post(
'/api/sendmail', {
data: { ...formData }
}
).then(res => {
}).catch(err => {
console.log(err)
})
The formData object holds the “Name,” “Email address,” and “Message” values, and we call '/api/sendmail.js' the moment the “Submit” button is clicked.
Creating the Config File for API Integration
The file '/api/sendmail.js' contains the code that sends the form values to both SendGrid and microCMS.
const request = require('request')
const sgMail = require('@sendgrid/mail')
const SENDMAIL_API_KEY = '******************' // Set your SendGrid API Key
const TEMPLATE_ID = '******************' // Set your SendGrid Template ID
const CMS_API_URL = 'https://yourdomain.microcms.io/api/v1/contact' // Set your microCMS endpoint
const CMS_API_KEY = '******************' // Set your microCMS X-WRITE-API-KEY
export default (req, res) => {
if(req.method == 'POST'){
sgMail.setApiKey(SENDMAIL_API_KEY)
// Get the POST data
const data = req.body.data
let adress_list = []
// Build the template data
let msg = {
'personalizations': [
{
'to': [
{'email': data['mail']}
],
'bcc': [,
{'email': '[email protected]'},
],
'dynamic_template_data': {
'name':data['name'],
'mail':data['mail'],
'text':data['text']
}
}
],
'from': {
'email': '[email protected]',
'name': 'Example Inc.'
},
'template_id': TEMPLATE_ID
}
const cmd_data = {
'name':data['name'],
'mail':data['mail'],
text:data['text']
}
// Send the email
sgMail
.send(msg)
.then(() => {
// Save to the CMS
request.post({
uri: CMS_API_URL,
headers: { 'Content-type': 'application/json', 'X-WRITE-API-KEY':CMS_API_KEY },
json: cmd_data
}, (err, response) => {
if(err){
res.statusCode = 500
res.send(err)
}
res.statusCode = 200
res.json({ status: response })
})
})
.catch((error) => {
console.log(error)
res.statusCode = 500
res.send(error)
})
}else{
res.statusCode = 400
res.send({error: new Error('invalid parameters')})
}
}
First, fill in the configuration values for SendGrid and microCMS.
Replace SENDMAIL_API_KEY, TEMPLATE_ID, CMS_API_URL, and CMS_API_KEY with the ones you set up yourself.
You also need to register the SendGrid API KEY with your host. In this article, we registered it with Vercel.
That’s all there is to it.
Testing It Out
Let’s try out the finished feature.
Fill in the form and click the “Submit” button.
① Check the auto-reply email
If the email you configured in SendGrid arrives at both the address entered in the [Email address] field and the admin address set in sendmail.js, you’re good.
--------------------------------------------
Dear John Smith,
Thank you for your inquiry.
We have received the following message:
[Name]
John Smith
[Email address]
[email protected]
[Message]
This is a test inquiry.
--------------------------------------------
② Check that form data is being stored
Open the microCMS admin panel—if your submission shows up there, you’re all set.
Conclusion
We’ve walked through how to build the form UI, send the email, and store the data—all in a serverless setup.
We hope this serves as a first step toward implementing features more nimbly, free from the burden of server management.
Reference: About SendGrid (Japanese)
Reference: microCMS
RECENT POSTS
Vol.203
What Is Design Management

Vol.202
Why Hiring No Longer Works— Redesigning Organizations and Decisions for an Uncertain Age
Vol.201
How to Choose a Branding Agency: 5 Criteria to Avoid Failure
Vol.200
Design Management: A Practical Guide for SMEs and Startups to Drive Real Results
Vol.199
How to Rebuild Brand Competitiveness: A Practical Guide to Brand Management for SMEs
Vol.198
From parent–child bonds to community: The future of education that nurtures diversity and designs relationships









