Create a Node.js Server Using Express & Deploy with Render: A Web App for Mailchimp Newsletter Subscribing

Create a Node.js Server Using Express & Deploy with Render: A Web App for Mailchimp Newsletter Subscribing

What does a server need to do? Why?

Serve data to clients!

How does this process work?

Suppose someone types Wikipedia.org into their browser. Their browser (the client), then sends a ‘request’ to the server. The server handles that ‘request’ and returns data in the form of a ‘response’ to the client. That response ends up being html with links for static resources such as css, javascript, and assets (i.e. images), to be presented to the client. In other words, the webpage!

flow chart for the client server relationship

Project Summary

Build a web app enabling visitors to subscribe to a Mailchimp newsletter.

TOOLS: NodeJS, npm, Express, and the Mailchimp api.

Deployed Web App: https://newsletter-signup-009x.onrender.com/

Repository Template (no API keys): https://github.com/michaelpgalen/newsletter-signup-template

Process

  1. Setup Directory
  2. Setup Server basics: listen on a port and handle GET requests from the root route
  3. Build and style webpages with HTML & CSS
  4. Handle POST requests for Newsletter Signups: making a GET request to Mailchimp database server
  5. Deploy using Render


Let’s Build!

Setup Directory

(assumes node.js and npm are installed)

  1. Create directory (mkdir Newsletter-Signup)
  2. Initialize NPM (npm init)
  3. Install ‘express’ package (npm install express)
  4. Create files: app.js, signup.html, success.html, failure.html (touch app.js success.html failure.html)
  5. Create a Public directory within Newsletter-Signup (this houses any static resources we want to serve to the client, like css files and images. These don’t require any preparation from the server. So instead of the kitchen preparing each meal per order (like the html pages being prepared per request), this is a buffet, food ready for the client to put on their plate.
  6. Create ‘images’ and ‘styles’ directories within ‘public’
  7. Create styles.css within public/styles

Screenshot of directory file structure
Directory file structure

Build Basic Server to handle GET requests

First, import and setup the ‘express’ package.

“Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.”

It helps make our code faster to write and easier to read.

  1. Setup express middleware to serve static resources from the ‘public’ folder.
  2. Setup express middleware to parse html form body data. We’ll use this to access our visitor’s input date from the SignUp form.

Screenshot of packages being set up in the app file
Packages being setup: Express and Node’s internal package ‘https’

Setup the server to listen on our localhost port 3000 for development.


app.listen(3000, console.log("Server running on PORT 3000")        


Handle GET requests at the directory root route (app.js).



app.get("/", function(req, res)
    res.sendFile(__dirname + "/signup.html")
}){        

Build and Style Webpages with HTML, CSS, and Bootstrap

  1. Use html boilerplates to create the basic document markup for each page.
  2. Copy and paste the html source code from a Bootstrap form example. Using a Bootstrap example speed’s up our styling (CSS writing), so we can focus on building the server. I used Bootstrap’s simple login form, then edited the html elements to match my needs.
  3. Make sure to add a link to Bootstrap’s CDN to the head of each html page.
  4. Copy and paste any custom CSS for this bootstrap example into our own styles.css file (path should be: public > styles > styles.css)

Screenshot of Bootstrap example plus the source code, annotated for our edits.
Bootstrap example + its source code, annotated for our needs.

Handle POST requests from the SignUp form

1. Create variables for the form input data (thanks to Express middleware we already set up).

2. Turn form data into a JSON string, exactly how Mailchimp’s API wants it based on their documentation. We already set up the Express middleware for JSON data with app.use(express.json()).

3. Make a POST request to the MailchimpAPI with options formatted to their specification. This is all written within the POST request to our server.

  • Create a const for the POST request, using Node’s internal https package. Make sure the module is required at the top of app.js file.
  • Based on the response status, serve our client either the success page or failure page.
  • Write the form data to the POST request with request.write(), followed by request.end().

Below is the code for our server handling POST requests at the root route, and making its own request to Mailchimp before sending a response.


app.post("/", function(req, res)
    const firstName = req.body.firstName;
    const lastName = req.body.lastName;
    const email = req.body.email;

    const postData = {
        members: [
            {
                email_address: email,
                status:"subscribed",
                merge_fields: {
                    FNAME:firstName,
                    LNAME:lastName
                }
            }
        ]
    }
    const jsonPostData = JSON.stringify(postData);

    console.log(req.body)
   
    const url = "https://us8.api.mailchimp.com/3.0/lists/YOUR_LIST_ID";
    const options = {
        method: 'POST',
        auth: "YOUR-API-KEY"
    }

    const request = https.request(url, options, function(response){
        console.log('status code: ' + response.statusCode)

        if (response.statusCode === 200) {
            res.sendFile(__dirname + "/success.html")
        } else {
            res.sendFile(__dirname + "/failure.html")
        }
    })
    request.write(jsonPostData)
    request.end()

})        

Deploy using Render.com

Render.com takes the place Heroku filled for a while, offering free hosting for small hobby web apps, and providing paid services when you need to scale. As described on Render’s website:

“Render is a unified cloud to build and run all your apps and websites with free TLS certificates, a global CDN, DDoS protection, private networks, and auto deploys from Git.” — Render.com

Plus, Render is setup with NodeJS.

Screenshot of Render.com homepage
Render.com

1) Create a free account on Render.com.

2) Create a new ‘Web Service’ project on Render.

3) If not done so already, push your directory to GitHub.

4) Connect Render to GitHub and select your Newsletter-Signup repository.

5) Settings for your Web Service:

  • Build command: npm install
  • Start command: node app.js

Settings for Render.com web service app
Settings for Render using npm

Your web service should be deployed shortly!


Resources

NodeJS install and docs: https://nodejs.org/en/

Express API reference: https://expressjs.com/en/api.html

Mailchimp API reference: https://mailchimp.com/developer/marketing/api/

Render docs: https://render.com/docs

To view or add a comment, sign in

More articles by Michael Galen

  • Reclaiming Cashmere for Classy Slow Fashion Brand

    Branding Case Study by MGalen Design Summary Services Logo Design Visual Branding Brand style guide Background Lambeaux…

  • Drum, Dance and Griots — Reflections on Senegal

    December 2024 — Senegal. Three weeks.

    1 Comment
  • Evolving an arts culture and deepening dance - reflections in Brazil

    Continued study is important in the Rejoice! Company. For my 2023 summer research, I immersed myself in Salvador…

  • Cuba Digest - Dance Research

    Embodying the feeling of a people To learn a cultural dance is to embody the feeling of a people. The feelings of a…

  • Front-end Engineering Take Home Project

    Background A few weeks into an interview process. I already passed the algorithmic test, my portfolio submission, and a…

  • A Process for Redesigning a Website

    Background Rejoice! Diaspora Dance Theater is an 8 year old non-profit dance theater company that has gown…

  • What ReactJS is NOT made for

    When a certain tool becomes incredibly popular, it’s easy to fall into the trap of choosing the tool before knowing the…

  • React Data Visualization Project

    Summary This project began as a coding challenge for a front-end developer job. This was my first React project.

    2 Comments
  • Design Thinking a Band

    Background Portland, Oregon has had a thriving samba scene since the early 2000s. Over the years we’ve had various…

  • Hackathons for Designers — Nerves & Saas

    Are hackathons nerve racking? Registering for a hackathon is welcoming a ton of uncertainty. Depending on your…

Others also viewed

Explore content categories