Creating a MERN Application with Deployment to Heroku. ( 2020 Beginner ) Part 1

Omar
10 min readJul 22, 2020
MERN: MongoDB, Express, Reactjs, NodeJs

PART 1: Getting Started

PART 2: Front-End

PART 3: Deployment!

Introduction To M.E.R.N

In this article, I will describe how to develop and deploy a full-stack web application utilizing the MERN stack. The MERN stack consists of MongoDB, Express, ReactJs, and NodeJs.

MongoDB is a Schemaless and Document Oriented database, which helps store the data for an application.

Express is a NodeJS web application framework, which makes it easy to create and maintain servers in NodeJs.

ReactJS is a library for building user interfaces.

NodeJS is used to write server-side applications.

Introduction To Heroku

Heroku is a platform as a service (PaaS) that enables developers to build, run, and operate applications entirely in the cloud. We will use Heroku in this tutorial to deploy our web application, which Heroku will host to the cloud.

Before we begin building!

In this tutorial, we will be creating a very simple Twitter chatting application. I will be using the Terminal provided to us by the Mac Operating System and Visual Studio Code as my choice of a text editor. Visual Studio Code can be downloaded HERE. I will also be using NPM, which is a package manager for the JavaScript programming language. NPM is included with NodeJs, which can be downloaded HERE.

Sections 1: Getting Started (Setting Up Back-End Folders/Files )

Step 1: Create a new project folder through terminal.

Step 2: change directory to simple_chat from the location in which it was initiated

Step 3: Inside of the projects folder, you now want to initialize a package.json file, which will set up a new npm package. (Npm is required)

Step 4: You will be prompted with a message that will guide you to create a package.json file. It only covers the most common items and tries to guess sensible defaults.

Step 5: Choose the default settings by pressing the enter/return button on your keyboard, then you will be asked if all the settings are OK.

Step 6: Inside of the projects folder, create an index.js file, which will contain our Server’s code.

Step 7: Inside of the projects folder, you will need to create a route folder, which will contain all of the endpoints routes.

Step 8: Inside of the projects folder, you will need to create a models folder, which will contain all of the schema maps to a MongoDB collection and defines the shape of the documents within that collection.

Step 9: Inside of the projects folder, you will need to create a config.js file, which will house our code to connect to MongoDB Atlas

Step 10: Inside of the projects folder, you will need to install all dependencies for the back-end. You will need the following packages,

  • cors
  • dotenv
  • express
  • mongoose
  • nodemon

Step 11: Open the project folder inside of Visual Studio Code.

Congrats, You have now completed the Back-End File Structure!! Now, Let’s confirm that your file structure matches the image below.

Sections 2: Setting Up The Back-end ( Server )

In this section, we will be building our back-end Server with NodeJs/Express but also connecting to MongoDB with mongoose.

Step 1: Inside of index.js, we will want to include the Express module, but in order to do that we will have to use the built-in “require” function. The “require” function is the easiest way to include modules that exist in separate files. Learn More Here

The following code is utilizing the required function and proceeds to return express() the function is a top-level function exported by the express module.

Step 2: Create a server with our “app” variable that will listen on port 5000 or process.env.PORT, which is a standard environment variable need for production, but while our server is in development it will be listening to port 5000. The app responds with “Hello World!” for requests to the root URL (/) or route.

Step 3: Utilizing Nodemon To Run Our Server. In the Projects Folder, you will need to run the following command.

Nodemon helps by automatically restarting the node application when file changes in the directory are detected.

Step 4: Congrats, the server is finally live on http://localhost:5000/ .

Sections 3: Connecting MongoDB to the Express server

Step 1: Go Sign-up for a free account at MongoDB Atlas. MongoDB Atlas is the easiest way to try out the database for free on AWS, Azure, or Google Cloud.

Step 2: You will be prompted to choose a path. Shared Clusters are free so we’ll be using that package!

Step 3: Creating a cluster, you will want to choose all the free options of MongoDB Atlas.

  • Aws as a cloud provider.
  • Recommend location can be set to default since MongoDB chooses the best option based on your location.
  • Cluster Tier can be left on M0 Sandbox, which is free!
  • You can change your cluster name if you would like to.
  • Once you have completed the steps listed above, click on “Create Cluster”.

Step 4: You will be redirected to the MongoDB Atlas dashboard, (Which can take a while to load).

Step 5: Click on the CONNECT button, which can be located under the name of your cluster.

Step 5: Setup connection security by allowing access from anywhere, which will allow Heroku access to our database and creating a username and password, all these settings will be necessary for the future.

Step 6: Choosing a connection method, which will connect to our NodeJS/Express App.

Select your driver and version:

Driver: NodeJs

Version: 3.6 or Later

Step 7: Inside of the Projects Folder, we will want to create a .env file, which will contain the connection string provided by MongoDB.

Step 8: Inside of the .env file, we will want to create an environment variable called, ”HOST”, set it equal to your connection string wrapped as Javascript String.

Step 9: Replace <password> with the password for the username user. Replace <dbname> with the name of the database that connections will use by default.

Step 10: Inside of config.js, we will use the environment variable and Mongoose to connect our MongoDB.

The following code above is used to connect to our MongoDB database. We are running an asynchronous function that will return a promise. Inside of the asynchronous function, the try and catch block will attempt to make the connection to the database, while any errors will be logged to the console.

Inside of the Try, We are using mongoose connect function, which takes two parameters, the first being the connection string, and the second is an object, which contains all the DeprecationWarning properties needed by Mongoose.

We are exporting the module to the index.js.

Step 11: Inside of index.js, we will import our function from config.js, then we will initializing our function.

Nodemon: If everything was done correctly, the console should look similar to the image below.

Congrats! You have successfully connected to MongoDB to an Express Server!

Sections 4: Creating mongoose post models and Express routes.

Step 1: Inside of the models' folder create a tweet.js file, which will contain our mongoose schema for our tweet.

Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.

The PostSchema defines a property in our documents that will be cast to its associated SchemaType. We have defined three different properties, which are name, tweet, and date. Each property has its own structure and SchemaType.

tweet.js will not be needed until we have created our post route.

Step 2: Inside the route folder, create a post.js file. This file will contain our code for the post request for sending data to our database.

The following code above is utilizing Express Router and the tweet model to create an API endpoint. The router.post() is a middleware sub-stack that handles POST requests and takes two arguments. The first argument is the route path, and the second is an asynchronous callback function. The callback function contains all the logic for the post request.

The try block will attempt to create a new post, which is utilizing the mongoose schema imported from models/tweets.js then the post is saved then sent to MongoDB.

The catch block will just console.log any errors.

Step 3: In order to connect the API route from the route/post.js to the main server, we will need to use the app.use() which is a middleware function in the index.js.

The following code below is using to arguments, the first argument is a path and the second argument is a callback function from feed.js. Which is imported with require(“./route/post”).

index.js

Awesome!! You have finally created the first API route!

The next step will be manual testing with Postman. Learn More Here.

Step 4: Testing with Postman

What is Postman? Postman is a collaboration platform for API development. Postman’s features simplify each step of building an API and streamline collaboration so you can create better APIs — faster.

We will be using the Postman application, and that can be downloaded from the Here.

Step 4.1: After you have downloaded the application, you will need to open it.

Step 4.2: In the upper top right-hand side, click on the “+” button.

A dashboard should then appear.

Step 4.3: We want to change the HTTP request from “GET” to the “POST” method because we are testing our post API route.

Step 4.4: Click on “body” and choose the “raw” option then change the type to “JSON”.

Step 4.4: Enter the Request Url, which is http://localhost:5000/api/post.

Step 4.5: Inside of the Body, we’re going to send some JSON data to our MongoDB Server.

Before You Send The Request, make sure your server is active, or you will get an error.

name” and “tweet” are both key values that our endpoint will be looking for inside of the request body.

Step 4.6: Checking for the response and assure that you received an HTTP status of 200 (ok).

We have finally finished our first Postman Test for our Api Post Route!

Back to finishing our backend API endpoints!

Step 5: Inside of the route folder, create a feed.js file. This file will contain our “GET” endpoint for getting all of the tweets from the MongoDB.

In the code listed above, the code is sending a “GET” request to the database to find all of the documents inside of the collections, which means we want to collect all of the tweets.

The asynchronous callback function is attempting to find all the documents inside of the collection called “Post” with a response of all the tweets in a JSON format.

Else, we will have an error message with a status of 500.

We will be exporting this module.

Step 6: Importing our “GET” route inside of index.js. This will allow us access to use the http://localhost:5000/api/feed URL.

Now our index.js should look similar to the image below.

Step 7: Testing our “GET” Route.

There is a much easier way to manually test our http://localhost:5000/api/feed route.

We can just type the URL in your google browser.

It will get all the data from the MongoDB database.

and BOOM !!! We have a GET Route!!

For now, we are going to leave the back-end alone, and continue to the Front-End of the application!

Continue To Part 2: Setting Up The Front-End ( Create-react-app)

--

--