On this site, I have created a Newsletter Subscribing system. I have used
Mailchimp API, and made a serverless function to talk with that. In this article, I will
guide you about this implementation process.
Collect your API key from Mailchimp > Account > Extras > API Keys > Create a Key.
Create an Audience from Mailchimp > Audience > All Contacts
Collect collection id from All Contacts > Settings > Audience name and campaign defaults > Audience ID
Now you have the followings:
API key
Audience ID
Step two - Setup Environment Variables
NextJS has built-in support for env. You need to create a .env.local file at the root of your project. Then paste your API key and Audience ID there like this
Step two - Create NextJS API
To create an API on NextJS, you need to create a file in the pages/api folder. I named I subscribe; you can name it whatever you like. The default function return from the file is the serverless function or API route.
pages/api/subscribe.js
Let's prepare a function that will prepare you the data you need to send to MailChimp.
All data you need to talk with Mailchimp is ready. Let's create the API now. This API shape is like this -