/heroku-tinkering

Playing around with deployment of a standard MERN app to Heroku

Primary LanguageJavaScript

MERN Stack with Heroku CI/CD - Boilerplate Setup

Barebones boilerplate setup for a MERN application linked to a CI/CD pipeline on Heroku to plug-and-play for a new project.

File Structure

+-- client
|      +-- public
|      +-- src
|      +-- build (gitignored)
|      +-- node_modules (gitignored)
|      +-- .gitignore (client)
|      +-- package.json (client)
|      +-- yarn.lock (client)
+-- server
|      +-- api
|      +-- models
|      +-- database.js
|      +-- index.js
+-- node_modules (gitignored)
+-- .env (gitignored - must add variables to use)
+-- .gitignore (server)
+-- package.json (server + deployment)
+-- yarn.lock (server)

Client

With Node installed, we can setup the client:

create-react-app client

Inside the client folder, we can install axios for sending HTTP requests

yarn add axios

For local development, we can add a proxy by adding this to the client package.json

"proxy": "http://localhost:5000"

Server

Standard Node.js + Express backend uses needs these dependencies installed:

yarn add express cors
  • express: Web application framework that provides a robust set of features for web and mobile applications
  • cors: middleware that can be used to enable CORS (Cross-Origin Resource Sharing)

Boilerplate server handles two basic endpoints:

  • POST /api/users: Add a user to the database given a name and an email
  • GET /api/users: Retrieve all users in the database

In the root folder, package.json includes the script

"start": "node server/index.js"

Database

Using MongoDB, these dependencies must be installed:

yarn add dotenv mongoose
  • dotenv: Zero-dependency module that loads environment variables from a .env file into process.env
  • mongoose: Elegant MongoDB object modeling for Node.js

Boilerplate database setup relies on a User model, composed of required strings: name and email

Set a database connection environment variable in the .env file as MONGODB_CONNECTION

mongodb+srv://username:<password>@<cluster>/<database>?retryWrites=true&w=majority

Deployment

Heroku needs the client to be built using a specific post-build script name in the root package.json

"heroku-postbuild": "cd client && npm install && npm run build"

If applicable, sign up for a new account

Using the Heroku CLI, we can login and initialize the application on Heroku

heroku login
heroku create <app-name>
git push heroku HEAD:master

On the Heroku console, add a pipeline to enable CI/CD with staging and production

image

Then, enable review apps for CI/CD on pull requests linked to a GitHub repo

image

Lastly, we can specify environment variables as Config Vars in the settings page (Staging, production, and review apps all need Config Vars setup)

image

Pipeline Deployments