Mailchimp bridge for JAMStack website

20th April, 2020 - 3 min. read - in Tutorials - Go to Index

If you run a JAMStack website and want to include a subscribe form to collect emails, there’s tons of options out there.

But if you, like me, want to have full control over the user experience, maybe you want to implement yourself the subscribe form and just call the service to store the email.

There are many services for email subscription. If your service of choice has API endpoints, then, follow this little tutorial about how to set up a little serverless lambda function that acts as a bridge between your static website and the external service (such as Mailchimp) in a secure way.

Security

You know, everything that sits in a frontend code is completely open and visible to anyone.

That means that drowning credentials in frontend code is not ideal, to say the least.

Usually, deadling with API services does require some credentials, so, here the strategy:

Webtask

There are many services that allow you creating lambda functions. Webtask is a neat and easy to use serverless service. It allows to publish a Node.js file transforming a pure js function in an API call.

A base-bone Webtask function looks like this:

module.exports = function (context, cb) {
  // the query parameters
  var param = context.query.myparam
  
  // performe something
  
  // call the callback when finished, passing an optional error object as a first parameter
  cb(null, { message: 'done!' })
 }

Extending the above example it’s a matter of adding a network request to a service to do the job.

MailChimp

MailChimp has an API option to work with it in headless mode. Here a sample about subscribing an email using axios:

axios({
  method: 'post',
  url: mailchimpUrl,
  data: {email:'some@email.com'}
})

The mailchimpUrl needs to be constructed this way:

let mailchimpUrl = `https://user:${MAILCHIMP_PASS}@${MAILCHIMP_URL}`

where MAILCHIMP_PASS is the token you can get from your Mailchimp account and MAILCHIMP_URL is the API endpoint with the list ID, such as:

const MAILCHIMP_URL = 'us17.api.mailchimp.com/3.0/lists/<YOUR-LIST-ID>/members'

The frontend

The frontend part can be anything you like plus an ajax request, such as:

document.querySelector('button').addEventListener('click', e => {
  
  axios.get(serviceUrl)
    .then(response => {
    console.log(response)
  }).catch(err => {
    console.log(err)
  })

})

The serviceUrl is the public Webtask URL with the query parameters appended to the URL (that URL will be provided by Webtask once you’ll publish a task with their CLI), because Webtask service responds to GET requests only: https://webtask.io/url?myparam=myval

So, you get the picture, so, the full source code here.


Spotted a typo or (likely) a grammar error? Send a pull request.