DEV Community

Cover image for How to add or update a Mailchimp subscriber using REST API with JavaScript
Abdulrahman Saleh Khamis
Abdulrahman Saleh Khamis

Posted on

How to add or update a Mailchimp subscriber using REST API with JavaScript

A great number of websites today use a contact form to get in touch with their visitors, and at the same time, they might want to add them to their Mailchimp list for future communication.

This is a simple way on how to add a new subscriber to your Mailchimp list, or update the subscriber's information if one already exists, with a simple snippet of JavaScript.

We will be using Mailchimp's REST API v3. We will not go over how to obtain your API key, as it is already covered here.

This is the whole code snippet:

const MAILCHIMP_API = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX-us1";
const MAILCHIMP_SERVER = "us1";
const MAILCHIMP_LIST_ID = "XXXXXXXXXX";
const auth = Buffer.from(`anystring:${MAILCHIMP_API}`).toString('base64');

const subscriber = {
  email_address: "test@example.com",
  status_if_new: "subscribed",
  merge_fields: {
    FNAME: "John",
    LNAME: "Smith",
  }
};

//Using Node's 'crypto', you can replace with any library that can generate MD5 hash for you
const subscriberHash = crypto
  .createHash("md5")
  .update(subscriber.email_address.toLowerCase())
  .digest("hex");

//Using Node's 'node-fetch'
const response = await fetch(
`https://${MAILCHIMP_SERVER}.api.mailchimp.com/3.0/lists/${MAILCHIMP_LIST_ID}/members/${subscriberHash}`,
  {
    body: JSON.stringify(subscriber),
    headers: {
      Accept: "application/json",
      'Content-Type': "application/json",
      Authorization: `Basic ${auth}`
    },
    method: "PUT"
  }
);

if (response.ok) {
  return { statusCode: response.status, body: response.statusText };
} else {
  throw new Error("Error requesting Mailchimp API");
}
Enter fullscreen mode Exit fullscreen mode

Here is a quick glance on what the variables mean:
${MAILCHIMP_API} You generate this from your Mailchimp portal, for example, XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX-us1
${MAILCHIMP_SERVER} Your Mailchimp server, for example, us1
${MAILCHIMP_LIST_ID} Find Your Audience ID

${subscriberHash} You need to generate MD5 hash of the email address of the subscriber. You can generate it easily with JavaScript using the following code:

const subscriberHash = crypto
    .createHash("md5")
    .update("test@example.com")
    .digest("hex");
Enter fullscreen mode Exit fullscreen mode

The API's request body contains the information of the subscriber that you want to add, or if the email already exists, update.

const subscriber = {
  email_address: "test@example.com",
  status_if_new: "subscribed",
  merge_fields: {
    FNAME: "John",
    LNAME: "Smith",
  }
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)