Skip to content

How to Build and integrate MailChimp Subscribe list with Node js

In this post I would like to show you a simple demo application which is build on top of express js framework, By following this tutorial you gonna build a subscribe form, through this form user can subscribe to MailChimp subscription list.

Let’s setup your express js application by creating package.json file and install required dependency libraries by issuing below commands.

Get Download link, by showing love:
[l2g name=”Download Source code” id=”4861″]

npm init // provide the information for the questions, if you want to avoid interactive question just pass --yes flag to npm init command.
npm install --save express body-parser mailchimp-api-v3 pug
touch index.js // window user just create a index.js file manually

By issuing the above commands you have installed dependencies and created you launch file called index.js. Now open index.js in your text editor and copy past the below code into it.

const express = require('express'); // import express module 
const bodyParser = require('body-parser'); // import body parser module
const app = express(); // create express instance 
app.use(bodyParser.json()); // register middleware to parse application/json 
app.use(bodyParser.urlencoded({extended: true})); // with extended true you can post nested object.

// home route
app.get('/', function (req, res) {
  res.send('Hello World!');
});

// start server at 8080 port.
app.listen(3000, function () {
  console.log('App listening on port 8080');
});

Server setup is ready, now issue below commands form command line to start HTTP server.

Desktop\mailChip> node index.js
App listening on port 8080

Then head over to http://localhost:8080, you will get Hello World! text on the browser screen.

Create a view file

You need a HTML view to show subscription form to the users, so lets create a directory called views and then create a pug template file which will hold the subscribe form markup.

$ mkdir views
$ touch email-subscribe.pug // window user just create a email-subscribe.pug file manually

Then copy below template markup to email-subscribe.pug.

doctype html  
html
  head
    title Arjunphp.com
    meta(name="viewport" content="width=device-width, initial-scale=1")
    link(rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css")
    script(src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js")
    script(src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js")  
    script(src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js")
    script(src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js")     
  body
    div.container
     div.page-header
        h1 Subscribe to MailChimp mailing list
     form(method='POST' action='/subscribe')       
          div.form-group
            label(for='email') Email:
            input#email.form-control(type='email', placeholder='[email protected]' name='email')
          div.form-group
            button.login.btn.btn-primary(type='submit') Subscribe

Then import pug into application, register pug template engine with middleware and render above created template for home page.

const express = require('express'); // import express module
....
....
const pug = require('pug');

app.set('views', './views'); // set views directory, this is defaults to the views directory in the application root directory.
app.set('view engine', 'pug'); // set view engine to pug

// home route
app.get('/', (req, res) => {
  res.render('email-subscribe'); // render pug template on home page. which is located at views/email-subscribe.pug
});
....
....
....

Now run the application

Desktop\mailChip> node index.js
App listening on port 8080

you should get following output:

Integrate MailChimp

We need to generate public API key from your MailChimp account and also identify your list ID. If you are not sure how to retrieve those, follow these links from MailChimp Knowledge Base to retrieve your account’s API key and find your list ID.

Now import mailChimp library which you have installed earlier at the beginning of the application setup, update your index.js file, import mailchimp-api-v3 module and create post handler route to handle from submissions, implemented logic for subscriptions. Here is the final index.js file.

const express = require('express'); // import express module
const bodyParser = require('body-parser'); // import body parser module
const pug = require('pug'); // pug template engine 
const Mailchimp = require('mailchimp-api-v3'); // node js mailchimp wrapper library
const app = express(); // create express instance
app.use(bodyParser.json()); // register middleware to parse application/json
app.use(bodyParser.urlencoded({ extended: true })); // with extended true you can post nested object.

app.set('views', './views'); // set views directory, this is defaults to the views directory in the application root directory.
app.set('view engine', 'pug'); // set view engine to pug

// home route
app.get('/', (req, res) => {
  res.render('email-subscribe'); // render pug template on home page. which is located at views/email-subscribe.pug
});

// handle subscribe form submit event
app.post('/subscribe', (req, res) => {
  const api_key = '....XXX.....'; // api key -
  const list_id = '....XXX.....'; // list id
  const mailchimp = new Mailchimp(api_key); // create MailChimp instance
  mailchimp.post(`lists/${list_id}`, { members: [{ // send a post request to create new subscription to the list
      email_address:req.body.email_address,
      status: "subscribed"
  }]
  }).then((reslut) => {
    return res.send(reslut);
  }).catch((error) => {
    return res.send(error);
  });
});

// start server at 3000 port.
app.listen(8080, () => {
  console.log('App listening on port 8080');
});
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments