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

Michaelpgalen
JavaScript in Plain English
5 min readJan 3, 2023

--

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!

Flowchart of the client server model.

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 the 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 app.js code, setting up the Express package and middleware
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 and CSS

  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 the Bootstrap example login form, plus, the source code.
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
    • Start command: node app.js
Screenshot of the settings in Render. Build command is npm install.
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

More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord.

Interested in scaling your software startup? Check out Circuit.

--

--