Mailchimp
Subscribe to a newsletter.
import mailchimp from '@mailchimp/mailchimp_marketing';
mailchimp.setConfig({
apiKey: process.env.MAILCHIMP_API_KEY,
server: process.env.MAILCHIMP_API_SERVER // e.g. us1
});
export default async (req, res) => {
const { email } = req.body;
if (!email) {
return res.status(400).json({ error: 'Email is required' });
}
try {
await mailchimp.lists.addListMember(process.env.MAILCHIMP_AUDIENCE_ID, {
email_address: email,
status: 'subscribed'
});
return res.status(201).json({ error: '' });
} catch (error) {
return res.status(500).json({ error: error.message || error.toString() });
}
};
Usage
1
Create Mailchimp Account
First, create a Mailchimp account. Then, generate an API key.
2
Find Audience ID
Each Mailchimp audience has a unique Audience ID. Retrieve the ID for the list you want to add a subscriber to.
3
Add Environment Variables
To securely access the API, we need to include the secret with each request. We also do not want to commit secrets to git. Thus, we should use an environment variable. Learn how to add environment variables in Vercel.