Web Development
Adding Users to Mailchimp via Firebase Cloud Functions
cover

Good to know beforehand

  1. Your Firebase account billing must be setup on at least Blaze before you can make external API requests from Cloud Functions. Blaze includes the free tier (but charges for anything that goes over instead of just stopping operations).

  2. After signing up for Mailchimp, you’ll need to create a Mailchimp API Key. Your Mailchimp API Key can be created and found in Profile/Extras/API Keys and will look something like this: a89821af195a6k06eb0976c41f4d31p1-us20

  3. You’ll need to create a List to hold your users. To distinguish these registered users from other users that may subscribe to your newsletter, you can name the list something like ‘Registered Users’. You’ll need your Maichimp Audience (or List) ID, which can be found by navigating to Audience/Manage Audience/Settings then Audience name and defaults. The Audience ID will look something like this: d08cc4c59b


Setup

  1. Install the Mailchimp API node package:
npm i mailchimp-api-v3
  1. In your ~/functions/src/index file:
// setup Firebase functions
import * as functions from 'firebase-functions';
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
admin.firestore().settings({ timestampsInSnapshots: true });

// import and initialize Mailchimp instance
const Mailchimp = require('mailchimp-api-v3');
const mailchimp = new Mailchimp('[YOUR MAILCHIMP API KEY]');

// create a Cloud Function which will trigger every time a new user is created
exports.userCreated = functions.auth.user().onCreate(user => {
  const { email, displayName } = user;

  // make Mailchimp API request to add user
  mailchimp
    .post('/lists/[YOUR MAILCHIMP LIST ID]/members', {
      email_address: email,
      status: 'subscribed',
      // optional: requires additional setup
      merge_fields: {
        // default empty string value included for type safety in case displayName is undefined
        NAME: displayName || ''
      }
    })
    .then(function(results) {
      console.log('Successfully added new Firebase user', email, 'to Mailchimp list');
    })
    .catch(function(err) {
      console.log('Mailchimp: Error while attempting to add registered subscriber —', err);
    });
});
  1. [Optional] To add additional user data to Mailchimp, you’ll need to configure and sync your list and API request. MailChimp calls additional user data “merge fields”.

    To add/edit merge fields of a list in Mailchimp, go to Audience/Manage Audience/Settings/Audience fields and *|MERGE|* tags and add the field you want.

    It will be prepopulated with default fields. You’ll need to delete any field you don’t want to provide via the API. If you leave undesired fields in the settings, you’ll have to submit empty values (with appropriate data types) in your API request, else Mailchimp will throw an error.

    In your API request, include a merge_field object with your list’s merge fields. To guard against null values of a user (ex. displayName), provide a default string value.

  2. cd into your ~/functions folder and run npm run build. Make sure your ~/functions/lib folder is empty.

  3. To deploy only your functions, run firebase deploy --only functions from your ~/functions folder.

Common Errors

  1. Error: getaddrinfo ENOTFOUND in Cloud Functions console: The Mailchimp request is failing, either due to Firebase blocking it (bc you have switched to a paid billing plan) or an incorrectly defined post request route (check your post path and make sure you you’re using the correct list ID and including ‘/members’ at the end of the path).

  2. Error: Cannot find module 'mailchimp-api-v3': You need to install the mailchimp-api-v3 package in your ~/functions folder (not the root directory).

  3. Error: The resource submitted could not be validated...'Data did not match any of the schemas described in anyOf.': Mailchimp is strict about what data you send it (including types). It is not recognizing what merge fields you are providing it, either bc your list isn’t setup with the desired merge fields, you aren’t providing some of the missing merge fields, or bc the data type of the merge field does not match what Mailchimp expects. See the optional Step 3.