Skip to main content

Deploy React App To Heroku

Deploy React App To Heroku Using Postgres & Express

Deploy React App To Heroku Using Postgres & Express

Heroku is an web application that makes deploying applications easy for a beginner.

Deploy React App To Heroku Using Postgres & Express

Heroku is an web application that makes deploying applications easy for a beginner.

# ##############################################################################
##### HEROKU TOOLBELT COMPLETE GUIDE ###########################################
################################################################################
# Installing Heroku toolbelt using command line
# For MacOS...
brew tap heroku/brew && brew install heroku
# For Ubuntu...
sudo snap install --classic heroku
# Other installation methods are
curl https://cli-assets.heroku.com/install.sh | sh # only for unix based systems, windows incompatible as it needs sudo
curl https://cli-assets.heroku.com/install-ubuntu.sh | sh # Ubuntu/Debian apt-get
yay -S heroku-cli # Arch linux, Note: This package is community maintained not by heroku
npm install -g heroku # This installation method is required for users on ARM and BSD...
############
# Verifying your installation
heroku --version
# Let's get started with heroku
heroku login # To login into the heroku toolbelt with your heroku account, this will open browser for you.
heroku login -i # If you prefer to stay in the command line environment, then you can execute this command
# Now navigate to your desired directory and create a blank heroku application
cd ~/myapp
heorku create
# If you are facing login issues, try to execute the following command
mv ~/.netrc ~/.netrc.backup
heroku login
# Uninstalling the heroku CLI
# For macOS
rm -rf /usr/local/heroku /usr/local/lib/heroku /usr/local/bin/heroku ~/.local/share/heroku ~/Library/Caches/heroku
# or you can try the below command also on macOS
brew uninstall heroku
rm -rf ~/.local/share/heroku ~/Library/Caches/heroku
# For Linux (Standalone installs)
rm /usr/local/bin/heroku
rm -rf /usr/local/lib/heroku /usr/local/heroku
rm -rf ~/.local/share/heroku ~/.cache/heroku
# For Linux (Debian and Ubuntu installs)
sudo apt-get remove heroku heroku-toolbelt
sudo rm /etc/apt/sources.list.d/heroku.list
#####################################################################################################
### Managing and deploying applications on Heroku (Using Git) ###################################
#####################################################################################################
cd myapp # Changing into the project directory
git init # Initializing the project into a git repository
git add -f example.json # Adding a perticular content of the project into the repository this will include the content from .gitignore
git add . # Adding all the contents of the project into the repository excluding .gitignore content
git commit -m "My first commit" # Commiting the content to the repository
heroku create appname # Creating a new application on Heroku here ( appname ) represent the name u give to your app
git remote -v # verifying that the remote is set to the heroku
heroku git:remote -a thawing-inlet-61413 # For an existing heroku app, you can add remote to the application
git remote rename heroku heroku-staging # renaming remotes
git push heroku master # Deploying code to the heroku application
git push heroku master --force # Force Pushing to heroku ( required if the remote contain works that u do not have locally )
git push heroku testbranch:master # Deploying code from a non-master branch to the heroku application
heroku create --ssh-git # ssh git transport for the application instead of https
git config --global url.ssh://git@heroku.com/.insteadOf https://git.heroku.com/ # For using ssh always
git config --global --remove-section url.ssh://git@heroku.com/ # To remove this rewrite setting run the command
#####################################################################################################
### Managing and deploying applications on Heroku (Using Docker) ###################################
#####################################################################################################
# Setting stack of your app to a Container
heroku stack:set container
heroku container:login # Login to the container resistry
git clone https://github.com/heroku/alpinehelloworld.git # Get sample code by cloning into the following repository
heroku create appname # Creating a heroku application here ( appname ) represent the name u give to your app
heroku container:push web # Build the image and push to Container Registry
heroku container:push --recursive # Pushing from the root directory of the project in recursive manner
heroku container:push web worker --recursive # Building the image and pushing to container resistry in recursive manner
heroku container:release web # Releasing the image to your application
heroku open # Open the application in the browser

Before you begin deploying, make sure to remove any console.log's or debugger's in any production code. You can search your entire project folder if you are using them anywhere.

You will set up Heroku to run on a production, not development, version of your application. When a Node.js application like yours is pushed up to Heroku, it is identified as a Node.js application because of the package.json file. It runs npm install automatically. Then, if there is a heroku-postbuild script in the package.json file, it will run that script. Afterwards, it will automatically run npm start.

In the following phases, you will configure your application to work in production, not just in development, and configure the package.json scripts for install, heroku-postbuild and start scripts to install, build your React application, and start the Express production server.

Phase 1: Heroku Connection

If you haven’t created a Heroku account yet, create one here.

Add a new application in your Heroku dashboard named whatever you want. Under the “Resources” tab in your new application, click “Find more add-ons” and add the “Heroku Postgres” add-on with the free Hobby Dev setting.

In your terminal, install the Heroku CLI. Afterwards, login to Heroku in your terminal by running the following:

heroku login

Add Heroku as a remote to your project’s git repository in the following command and replace <name-of-Heroku-app> with the name of the application you created in the Heroku dashboard.

heroku git:remote -a <name-of-Heroku-app>

Next, you will set up your Express + React application to be deployable to Heroku.

Phase 2: Setting up your Express + React application

Right now, your React application is on a different localhost port than your Express application. However, since your React application only consists of static files that don’t need to bundled continuously with changes in production, your Express application can serve the React assets in production too. These static files live in the frontend/build folder after running npm run build in the frontend folder.

Add the following changes into your backend/routes.index.js file.

At the root route, serve the React application’s static index.html file along with XSRF-TOKEN cookie. Then serve up all the React application's static files using the express.static middleware. Serve the index.html and set the XSRF-TOKEN cookie again on all routes that don't start in /api. You should already have this set up in backend/routes/index.js which should now look like this:

// backend/routes/index.js
const express = require('express');
const router = express.Router();
const apiRouter = require('./api');
router.use('/api', apiRouter);
// Static routes
// Serve React build files in production
if (process.env.NODE_ENV === 'production') {
const path = require('path');
// Serve the frontend's index.html file at the root route
router.get('/', (req, res) => {
res.cookie('XSRF-TOKEN', req.csrfToken());
res.sendFile(
path.resolve(__dirname, '../../frontend', 'build', 'index.html')
);
});
  // Serve the static assets in the frontend's build folder
router.use(express.static(path.resolve("../frontend/build")));
  // Serve the frontend's index.html file at all other routes NOT starting with /api
router.get(/^(?!\/?api).*/, (req, res) => {
res.cookie('XSRF-TOKEN', req.csrfToken());
res.sendFile(
path.resolve(__dirname, '../../frontend', 'build', 'index.html')
);
});
}
// Add a XSRF-TOKEN cookie in development
if (process.env.NODE_ENV !== 'production') {
router.get('/api/csrf/restore', (req, res) => {
res.cookie('XSRF-TOKEN', req.csrfToken());
res.status(201).json({});
});
}
module.exports = router;

Your Express backend’s package.json should include scripts to run the sequelize CLI commands.

The backend/package.json's scripts should now look like this:

"scripts": {
"sequelize": "sequelize",
"sequelize-cli": "sequelize-cli",
"start": "per-env",
"start:development": "nodemon -r dotenv/config ./bin/www",
"start:production": "node ./bin/www"
},

Initialize a package.json file at the very root of your project directory (outside of both the backend and frontend folders). The scripts defined in this package.json file will be run by Heroku, not the scripts defined in the backend/package.json or the frontend/package.json.

When Heroku runs npm install, it should install packages for both the backend and the frontend. Overwrite the install script in the root package.json with:

npm --prefix backend install backend && npm --prefix frontend install frontend

This will run npm install in the backend folder then run npm install in the frontend folder.

Next, define a heroku-postbuild script that will run the npm run build command in the frontend folder. Remember, Heroku will automatically run this script after running npm install.

Define a sequelize script that will run npm run sequelize in the backend folder.

Finally, define a start that will run npm start in the `backend folder.

The root package.json's scripts should look like this:

"scripts": {
"heroku-postbuild": "npm run build --prefix frontend",
"install": "npm --prefix backend install backend && npm --prefix frontend install frontend",
"dev:backend": "npm install --prefix backend start",
"dev:frontend": "npm install --prefix frontend start",
"sequelize": "npm run --prefix backend sequelize",
"sequelize-cli": "npm run --prefix backend sequelize-cli",
"start": "npm start --prefix backend"
},

The dev:backend and dev:frontend scripts are optional and will not be used for Heroku.

Finally, commit your changes.

Phase 3: Deploy to Heroku

Once you’re finished setting this up, navigate to your application’s Heroku dashboard. Under “Settings” there is a section for “Config Vars”. Click the Reveal Config Vars button to see all your production environment variables. You should have a DATABASE_URL environment variable already from the Heroku Postgres add-on.

Add environment variables for JWT_EXPIRES_IN and JWT_SECRET and any other environment variables you need for production.

You can also set environment variables through the Heroku CLI you installed earlier in your terminal. See the docs for Setting Heroku Config Variables.

Push your project to Heroku. Heroku only allows the master branch to be pushed. But, you can alias your branch to be named master when pushing to Heroku. For example, to push a branch called login-branch to master run:

git push heroku login-branch:master

If you do want to push the master branch, just run:

git push heroku master

You may want to make two applications on Heroku, the master branch site that should have working code only. And your staging site that you can use to test your work in progress code.

Now you need to migrate and seed your production database.

Using the Heroku CLI, you can run commands inside of your production application just like in development using the heroku run command.

For example to migrate the production database, run:

heroku run npm run sequelize db:migrate

To seed the production database, run:

heroku run npm run sequelize db:seed:all

Note: You can interact with your database this way as you’d like, but beware that db:drop cannot be run in the Heroku environment. If you want to drop and create the database, you need to remove and add back the "Heroku Postgres" add-on.

Another way to interact with the production application is by opening a bash shell through your terminal by running:

heroku bash

In the opened shell, you can run things like npm run sequelize db:migrate.

Open your deployed site and check to see if you successfully deployed your Express + React application to Heroku!

If you see an Application Error or are experiencing different behavior than what you see in your local environment, check the logs by running:

heroku logs

If you want to open a connection to the logs to continuously output to your terminal, then run:

heroku logs --tail

The logs may clue you into why you are experiencing errors or different behavior.

If you found this guide helpful feel free to checkout my github/gists where I host similar content:

bgoonz’s gists · GitHub

Alternate Instructions:

Deploy React and Express to Heroku

You've got a React app, and an API server written in Express or something else. Now -- how do you deploy them both to a server?

There are a few ways to do this:

  • Keep them together -- Express and React files sit on the same machine, and Express does double duty: it serves the React files, and it also serves API requests.
    • e.g., a DigitalOcean VPS running Express on port 80
  • Split them apart -- Host the Express API on one machine, and the React app on another.
    • e.g., React app served by Amazon S3, API server running on a DigitalOcean VPS
  • Put the API behind a proxy -- Express and React app files sit on the same machine, but served by different servers
    • e.g., NGINX webserver proxies API requests to the API server, and also serves React static files

This article will cover how to keep them together. We'll build the Express server to serve React's static files in addition to providing an API, and then deploy it to Heroku. Heroku is easy to deploy to and free to get started with.

Make a Heroku Account

If you don't have one already, go here and sign up. It's free.

Install Heroku Toolbelt

Heroku comes with a commandline command they call a "toolbelt." Follow the instructions here to install it. (On a Mac with Homebrew, just brew install heroku).

The App

We'll build a password generator. Every time you load the app or click Get More you'll get 5 random paswords.

Finished product

Just a quick disclaimer: this is just meant as a demo! I don't recommend using some random internet thing that generates passwords on the server to generate your own real passwords ;)

Create the Express App

Make a parent directory to contain everything. Call it rando or whatever you want.

$ mkdir rando; cd rando

Initialize the project with Yarn or NPM:

$ yarn init -y
  # or npm init -y

We need 2 packages: Express itself, and a password generator. Install those now:

$ yarn add express password-generator

Create a file called index.js, which will be the Express app, and type this in:

const express = require('express');
const path = require('path');
const generatePassword = require('password-generator');

const app = express();

// Serve static files from the React app
app.use(express.static(path.join(__dirname, 'client/build')));

// Put all API endpoints under '/api'
app.get('/api/passwords', (req, res) => {
  const count = 5;

  // Generate some passwords
  const passwords = Array.from(Array(count).keys()).map(i =>
    generatePassword(12, false)
  )

  // Return them as json
  res.json(passwords);

  console.log(`Sent ${count} passwords`);
});

// The "catchall" handler: for any request that doesn't
// match one above, send back React's index.html file.
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname+'/client/build/index.html'));
});

const port = process.env.PORT || 5000;
app.listen(port);

console.log(`Password generator listening on ${port}`);

We're also going to need a "start" script in package.json, so that Heroku knows how to start the app. Open package.json and add a scripts section at the bottom. The full file should look something like this:

{
  "name": "rando",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "dependencies": {
    "express": "^4.15.3",
    "password-generator": "^2.1.0"
  },
  "scripts": {
    "start": "node index.js"
  }
}

Test It

It's always good to make sure things are working as you go along. Much better than getting to the end and realizing nothing works. So, let's try it out.

Start up the Express app by running:

$ yarn start

Open up your browser and go to http://localhost:5000/api/passwords. You should see something like this:

Password generator working

Set Up Heroku

Now we'll deploy the app to Heroku, make sure it works, and then we'll add React to the mix.

Git Init

Heroku needs your project to have a Git repository, so we'll create one along with a .gitignore file to ignore node_modules, and then commit the code:

$ git init
$ echo node_modules > .gitignore
$ git add .
$ git commit -m "Initial commit"

Now we're ready for Heroku. Run its 'create' command:

$ heroku create

And you'll see something like this:

Heroku created

To make it work, we just need to push up our code by running:

$ git push heroku master

It will print out a bunch of stuff, and then the app will be live. One of the last lines will tell you the URL of the app:

My Heroku URL

Now you can go to <your url>/api/passwords and make sure it works.

Woohoo! You've got an app live on the real internet! Except it's not very nice to use, yet. Let's add a React frontend now.

Create the React App

We're going to use Create React App to generate a project. Remember that we decided the React app would live in the "client" folder? (we did, back when we set up Express to point to "client/build" for static assets).

If you don't have Create React App installed yet, do that first:

$ yarn global add create-react-app
# or npm install -g create-react-app

Generate the React app inside the Express app directory:

$ create-react-app client

Create React App will proxy API requests from the React app to the Express app if we add a "proxy" key in package.json like this:

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

This goes in client/package.jsonnot in the Express app's package.json, and it will be ignored by Heroku after deploying.

Open up src/App.js and replace it with this:

import React, { Component } from 'react';
import './App.css';

class App extends Component {
  // Initialize state
  state = { passwords: [] }

  // Fetch passwords after first mount
  componentDidMount() {
    this.getPasswords();
  }

  getPasswords = () => {
    // Get the passwords and store them in state
    fetch('/api/passwords')
      .then(res => res.json())
      .then(passwords => this.setState({ passwords }));
  }

  render() {
    const { passwords } = this.state;

    return (
      <div className="App">
        {/* Render the passwords if we have them */}
        {passwords.length ? (
          <div>
            <h1>5 Passwords.</h1>
            <ul className="passwords">
              {/*
                Generally it's bad to use "index" as a key.
                It's ok for this example because there will always
                be the same number of passwords, and they never
                change positions in the array.
              */}
              {passwords.map((password, index) =>
                <li key={index}>
                  {password}
                </li>
              )}
            </ul>
            <button
              className="more"
              onClick={this.getPasswords}>
              Get More
            </button>
          </div>
        ) : (
          // Render a helpful message otherwise
          <div>
            <h1>No passwords :(</h1>
            <button
              className="more"
              onClick={this.getPasswords}>
              Try Again?
            </button>
          </div>
        )}
      </div>
    );
  }
}

export default App;

You can update the CSS too, if you like (in src/App.css):

.App {
  text-align: center;
  font-family: "Courier New", monospace;
  width: 100%;
}

h1 {
  font-weight: normal;
  font-size: 42px;
}

.passwords {
  list-style: none;
  padding: 0;
  font-size: 32px;
  margin-bottom: 2em;
}

.more {
  font-size: 32px;
  font-family: "Courier New", monospace;
  border: 2px solid #000;
  background-color: #fff;
  padding: 10px 25px;
}
.more:hover {
  background-color: #FDD836;
}
.more:active {
  background-color: #FFEFA9;
}

I also recommend opening up src/index.js and removing the call to registerServiceWorker() at the bottom, since it can cause some confusing caching issues (like preventing you from accessing the API endpoints in a browser after you load the React app once).

Now start up the React app by running yarn start inside the client folder.

Make sure the Express app is running too: run yarn start from its folder as well.

Go to http://localhost:3000 and the app should be working! Now we can deploy the whole thing to Heroku.

Deploying to Heroku

When you deploy the app with the git push heroku master command, git copies all the checked-in files up to Heroku. There are two complications now:

  • We need to check in the new client code
  • Express depends on the built client code in client/build, which we don't have yet, and which we'd rather not check in to git.

What we'll do is tell Heroku to build the React app after we push up the code, and we can do that by adding a "heroku-postbuild" script in the top-level (Express app's) package.json.

Using Yarn

If you're using Yarn, the script looks like this:

"scripts": {
  "start": "node index.js",
  "heroku-postbuild": "cd client && yarn && yarn run build"
}

This tells Heroku "hey, after you're done doing what you do, go into the client folder and build my React app." The yarn run build script will kick off Create React App's production build, which will put its output files in the client/build folder so Express can find them.

Using NPM

If you're using NPM, the script will look like this:

"scripts": {
  "start": "node index.js",
  "heroku-postbuild": "cd client && npm install && npm run build"
}

This tells Heroku "hey, after you're done doing what you do, go into the client folder and build my React app." The npm run build script will kick off Create React App's production build, which will put its output files in the client/build folder so Express can find them.

Thanks to Matthew Locke and Babajide Ibiayo in the comments for how to get this working with NPM.

Time to Deploy

Once you have configured the heroku-postbuild step for Yarn (or NPM), add everything to git and commit it. Make sure to run this from the top-level rando directory, not inside client:

$ git add .
$ git commit -m "Ready for awesome"

If you run git status now, you should see no red items.

Then you can deploy the app by running:

$ git push heroku master

It again prints out your app's hostname. Mine is https://glacial-brook-33351.herokuapp.com/. Go there and try it out!

Congrats, you've got a React + Express app in production ;)

Get the Code

The complete app can be found on Github, and the README there explains how to deploy it.

Check out the npm branch with git checkout npm if you want to use NPM. From there, the deploy will differ slightly -- run git push heroku npm:master to deploy the npm branch insead of master.

Deploy MERN App To Heroku:

Source: Article

How To Deploy a Full-Stack MERN App with Heroku/Netlify

This post is intended to be a guide for those that want to deploy a full-stack MERN app. It will be v...

Cover image for How To Deploy a Full-Stack MERN App with Heroku/Netlify

stlnick profile image Nick Aug 29, 2020 ・Updated on Aug 31, 2020 ・12 min read

This post is intended to be a guide for those that want to deploy a full-stack MERN app. It will be very specific on steps so it's a bit of a read, however, it will ensure there is minimal to no confusion on how to get from point A to point B.

Feel free to hop around if you've got some of these steps done, know how to do them already, what have you.

If this is your first time don't intimidate yourself! Just read and complete each step one at a time.

NOTE: This guide is based on my specific project structure and this works well for it. There are definitely other ways to deploy and other ways people prefer to have their project structured.

Project Context

So you've got a cool project you'd like to show off to the world, how do we deploy a full-stack MERN app?

Let's first get some basics out of the way and context on how I did this: my project structure, basic configuration, and why I chose this way of deployment.

What is MERN?

MERN stands for MongoDB - Express - React - Node.

  • MongoDB for the database
  • Node & Express for the server-side
  • React for the client-side

There's also the MEAN stack, which uses Angular instead of React, and the... MEVN(?) stack... whatever, it uses Vue instead of React or Angular.

Project Structure

One thing that is definitely dev to dev, company to company, is how we structure our project as a whole. By this I mean where our directories are in relation to each other. Here is my fully collapsed root directory to show you the top-level:

Root directory structure

Just three things:

  • My VS Code settings and extensions JSON files
  • Client-Side Code
  • Server-Side Code

I like this structure because to me there's a clear separation of responsibilities. It makes it easier for me to work on one or the other by just collapsing that whole folder. For instance if there's some UI feature I want to add/fix/alter then I have no reason to open my server directory.

I feel it makes it logical and simple to work with. Again, this is absolutely personal preference. This is also a big reason why this project was deployed in the way this guide will describe.

Some Options for Deployment

Credit to Dave Ceddia for putting this list together - this was found in a blog post of his.

  1. Keep client and server together
    • Your Express and React files will live on the same machine and Express will both serve your API requests and the React files as well
  2. Put your API behind a proxy
    • This will allow your Express and React files to still live on one machine but each will be served by a different server
  3. Split client and server apart (the option for this guide)
    • Host your Express API on one machine and the React App on another

Deployment is not something I have a ton of experience with so the first two options I've never attempted.

I do know that in some cases for deployment on one machine a lot of devs must nest their entire client directory inside of server. This was a big reason I went the route I did for deployment because for me I wanted to keep the structure pictured above with a clear separation of client-side code and server-side code.

Project Configuration

The base of the project I deployed was the Create-React-App, which comes with a webpack.config.js and other basic configurations out of the box, for the front-end.

I also used Webpack for the server directory as well to allow all those beautiful imports and exports to work for me and allow me to separate responsibilities on the server-side.

Here's a shot of the client and server directories expanded just to show you how I have it setup. There's only a couple things that will need to be there for this project structure to work which I'll point out.

Expanded root directory

Each directory, client and server, needs:

  • .gitignore
    • To ignore the files and directories we don't want stored in our repo
  • package.json
    • To specify our separate dependencies and devDependencies
  • webpack.config.js
    • The client doesn't have one because Create-React-App again provides one out of the box so I didn't need to specify it there

You may have noticed I have a yarn.lock inside client and a package-lock.json inside server. I intentionally use yarn for client-side and npm for server-side because it helps me just keep those separate in my mind. I know if I'm using yarn then I'm in client and if I'm using npm I'm in server. Once again just a personal preference - you could use yarn or npm for both and have no issues.

You may have also noticed the Procfile which we'll get to later in the guide. As a teaser this will be needed by Heroku to deploy our server code which is why it lives inside of server.

Now that we have some context on how my project is setup let's talk about the actual process of deploying.

Deployment Process

What we're going to do specifically is host our server code on Heroku and our client code on Netlify. So our React App hosted on Netlify will make API requests to our Express API hosted on Heroku.

This will assume that you have both client and server running correctly and that you have already connected your app to a hosted database on MongoDB.

Steps

  1. Create a Netlify account or sign in if you have one

  2. Create a Heroku account or sign in if you have one

  3. Install the Heroku CLI

    • There is instructions on how to do this for both Mac and Windows in this linked article
  4. Go to your terminal and type heroku login

    • This will prompt you to press any key, once you do it will take you to your browser where you will just need to click 'Log In'.
    • Once this is successful you can close that browser window and navigate to your text editor now with your project open
  5. Create a file named Procfile, no file extension, in /server directory.

    • Include this text and this text only in the Procfile
      • web: node dist/main.js
    • This tells Heroku what to do after building our app - which specifically is to run our bundled file from webpack with all of our server logic inside it
    • If we didn't include this it would likely build just fine but never actually start our server
  6. Now we must add to our server/package.json the following block:

    • You can more than likely add this anywhere (not nested in any other property) but I added it right below the "main" property near the top in the server/package.json.

    • Recommended to check your node and npm versions first to know which versions to put in this next block. While it likely won't break your app with a slightly different version it is safer to specify the versions you used in development to prevent unexpected behavior.

    • node -v or node --version to check your Node version

    • npm -v or npm --version to check your npm version

    • Add those versions that return to this engines property if they're different than mine.

    • I used "14.x" for node to say, "As long as the major version of Node is 14 then use the latest minor version. Major version releases are when they're likely to be breaking changes which we want to avoid.

      "engines": { "node": "14.x", "npm": "6.14.7" },

  7. We need to allow access to your MongoDB database now from a new IP address. For simplicity, I added all IP addresses to be allowed.

  8. In development I had the express server listen to localhost:5000 to run there and my react app ran on port 3000. We must change what this Express server will listen for to app.listen(process.env.PORT || 5000)

    • So this will tell the server to listen to the .env environment variable PORT which we should not have set in our own .env file. OR it will listen to port 5000.

    • The process.env.PORT will be set by Heroku's .env - they essentially will tell our server which port to listen to.

    • If there is no such process.env.PORT, in other words there is no .env file that has been configured, then it will default to 5000. This will allow us to keep that code in and be able to run it in our local development environment on port 5000 because we do not have a .env variable PORT.

      // server.js

      /* Other code... */

      app.listen(process.env.PORT || 3000);


    Ensure in your terminal that you are inside the root of the project you are deploying for these next two steps


  9. Now back inside your Terminal the next command we type is heroku git:remote -a <project-name>. Replace <project-name> with really whatever name you want - I recommend the name of your project to keep it simple. So for example it will look like heroku git:remote -a my-project.

    • This is going to create a remote connection with Heroku specifically and also create a branch on that remote for you and your app name will be the name you provided, such as my-project above. Next we're going to actually push our server code to that remote Heroku branch.

      heroku git:remote -a my-project

  10. The command we need to push our server code specifically, because we have the separation of client and server in our project structure, is git subtree push --prefix server heroku master

*   This is telling git to push a subtree, or in other words a _subdirectory_, from our current git repo. The `--prefix` flag comes before that subdirectory that we want to push, in our case it is `server`. And lastly we're telling it to push to the remote `heroku` our `master` branch.

    git subtree push --prefix server heroku master
    

* * *

**IF you want to test and ensure that you've deployed your server to Heroku just add in a test route in your `server.js` like:**  

    app.get('/', (req, res) => { res.send('Hello from Express!')
    

You can view your app by:  
\- Copy and pasting the url that will appear in your Terminal after successfully pushing your code to the remote Heroku branch  
\- Navigating to your project on [the Heroku website](http://heroku.com/) and there will be a button that says 'View App' - click it and it will take you there

*   If you see the 'Hello from Express!' (or whatever test message you used) then that means your server is running correctly

* * *
  1. Now for our MongoDB connection to work we must define an environment variable for Heroku to store our MongoDB connection string.
> We want to keep our connection string secret as we don't want anybody able to connect to our database and change, delete, add things etc.  
> In our local build the connection string, is stored in our `.env` file inside of `/server`. I named by connection string `MONGODB_URI`. You can do this next step on the Heroku CLI or on the Heroku website.  
> I recommend the website it's more straightforward and you don't have to worry about escaping special characters. I'm going to describe the next steps going through the website.

*   Navigate to your dashboard on Heroku
*   Click on your project name that will be present from our previous steps where we created our remote branch and pushed the code
*   Navigate to the Settings tab near the top
*   The second section is 'Config Vars' - click on 'Reveal Config Vars'
*   You'll see two inputs:
    *   One is the name of your environment variable - name this **whatever you have it named in your local build**. For me that is `MONGODB_URI`.
    *   Second is the value - paste your whole connection string here that you should copy from your `.env` file directly to avoid any typos.
*   Then just click 'Add' and our MongoDB connection environment variable is set. ![Heroku site config vars](https://res.cloudinary.com/practicaldev/image/fetch/s--D4fJ2hPQ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/7ewhhh5fybrk94691c6i.png)

* * *

Our `server` code is officially deployed and configured correctly. Now onto the `client` code with Netlify.

* * *
  1. Next is to deploy the front-end React code in /client to Netlify. Login to Netlify if you haven't already, the default tab should be Sites or just navigate to that tab.

  2. LASTLY after we deploy our front-end React code we must ensure any requests we're sending from the client-side is changed to use our Heroku URL now instead of localhost.

*   In my structure the requests were being made from `client/api/index.js` so navigate to that file and _any request that contains_ `http://localhost:5000` must be replaced by your Heroku URL.

    // Before
    const res = await fetch('http://localhost:5000/scores/'
    
    // After
    const res = await fetch('https://my-project.herokuapp.com/scores/')
    
    // 'my-project' in the URL will either be the auto-generated
    // name from Netlify or if you changed the name it will
    // be the name you gave it

Ensure that you push these changes up to GitHub. Netlify will trigger a redeploy when they detect changes to your master branch. So for this to work you must make those changes apparent to Netlify essentially.

Now any request, instead of going to your local server you've ran while developing, will go to the hosted server you just deployed to Heroku with all of your Express Routes still intact and functioning properly.


It's undoubtedly a long process to get this done. But the important thing is that it can be done!

It's awesome to see the things we build on our local machine in development. After this though you can send a live link to your friends, colleagues, etc. for them to check it out!

This is awesome to have a live example as well for anyone looking for a job. Being able to not only have a link on your Resume or Portfolio site to the code on GitHub but for recruiters, managers, whoever to be able to see the project in action is huge!

Let me know in the comments...

... how you like to deploy! Link me an article, give me a brief overview, or whatever you want. I'd love to hear of the other ways devs get their projects out there for the world to see and enjoy!

Source

Discover More:

Popular posts from this blog

These Are The Bash Shell Commands That Stand Between Me And Insanity

These Are The Bash Shell Commands That Stand Between Me And Insanity These Are The Bash Shell Commands That Stand Between Me And Insanity I will not profess to be a bash shell wizard… but I have managed to scour some pretty helpful little scripts from Stack Overflow and modify… These Are The Bash Shell Commands That Stand Between Me And Insanity I will not profess to be a bash shell wizard… but I have managed to scour some pretty helpful little scripts from Stack Overflow and modify them to suit my needs. All of these commands are for Ubuntu/WSL … some may work in other scenarios but I can’t guarantee it. ...
Deploy-React-App-To-Heroku-Using-Postgres Deploy React App To Heroku Using Postgres & Express Heroku is an web application that makes deploying applications easy for a beginner. Deploy React App To Heroku Using Postgres & Express Heroku is an web application that makes deploying applications easy for a beginner. Before you begin deploying, make sure to remove any console.log ’s or debugger ’s in any production code. You can search your entire project folder if you are using them anywhere. You will set up Heroku to run on a production, not development, version of your application. When a Node.js application like yours is pushed up to Heroku, it is identified as a Node.js application because of the package.json file. It runs npm install automatically. Then, if there is a heroku-postbui...

Data Structures Resources

Data Structures & Algorithms Resource List Part 1 Data Structures & Algorithms Resource List Part 1 Guess the author of the following quotes: Data Structures & Algorithms Resource List Part 1 Guess the author of the following quotes: Talk is cheap. Show me the code. Software is like sex: it’s better when it’s free. Microsoft isn’t evil, they just make really crappy operating systems. Update: Here’s some more: ...