Skip to content

Instantly share code, notes, and snippets.

@caprosset
Last active November 25, 2020 22:04
Show Gist options
  • Save caprosset/822ce7aef8690ff51bdfba25eeb09acc to your computer and use it in GitHub Desktop.
Save caprosset/822ce7aef8690ff51bdfba25eeb09acc to your computer and use it in GitHub Desktop.
Heroku deployment - M3

PROJECT 3 - DEPLOYMENT ON HEROKU

1. SIGNUP/LOGIN TO HEROKU

Run the following commands in your terminal (in your SERVER/BACKEND repo):

heroku --version

If it gives you a version, it means that the Heroku CLI interface is correctly installed.
If not, create an account in Heroku (https://signup.heroku.com/) and repeat.

Once you have Heroku installed, run this command in your terminal to login:

heroku login

Type 'enter' or any key and you will be redirected to a browser window where you'll be able to login to your Heroku account.

   

2. CREATE THE APP IN HEROKU

2.1. Go to your dashboard, and click on the top right button that says "New: > 'Create New app'

 

2.2. Connect Heroku to your local repo

In the root folder of your SERVER/BACKEND repo, run the following command to add heroku remote (connect your local server repo to your app on heroku):

$ heroku git:remote -a name-of-the-app

You will find that command under the "Create a new Git repository" section in your dashboard)

Check that the remote has been correctly added to your project.
You should see a new remote 'heroku' in addition to 'origin' (Github):

$ git remote -v

 

2.3. Deploy your server to Heroku

First, commit your last changes on 'master' branch and push them to Github. On the master branch of your SERVER/BACKEND repo:

$ git add .
$ git commit -m 'Add last changes'
$ git push origin master

then deploy them as well to Heroku pushing them to your 'heroku' remote:

$ git push heroku master

   

3. CREATE THE PRODUCTION BUILD OF YOUR APP

3.1. Create the variables in .env files

Open your CLIENT/FRONTEND repo in your terminal, and run the following command:

touch .env.development .env.production

This will create 2 new files in your frontend root folder.

Inside the file .env.development, write this line:

REACT_APP_API_URL=http://localhost:5000

In the .env.production, write this line (by changing name-of-your-app by the name of your app that you have chosen in Heroku):

REACT_APP_API_URL=https://name-of-your-app.herokuapp.com

Very important: do not add any slash at the end of that url

N.B.: The REACT_APP env variables are specific to create-react-app package.

 

3.2. Replace the variables in your code

In your CLIENT/FRONTEND codebase, replace all base urls from your axios/API calls to the server ('http://localhost:5000) by this variable. Example of how to use it in your code: axios.post(process.env.REACT_APP_API_URL + '/api/projects', body)

If you are also using an external API, create a variable for the key/token of that API in both files (.env.development and .env.production), starting with "REACT_APP_", and replace it wherever it is present in your code.
Example of how to use it in your code: process.env.REACT_APP_MAPBOX_API_KEY

 

3.3 Create the build

Create a /build directory in your project root and let it empty.
This folder will include index.html and all your minified and bundled React files.

The following command will prepare the code that is ready to deploy in production (minifies and bundles the files in order to serve them from the server side).
Still in the CLIENT/FRONTEND side, run in your terminal:

npm run build

Once it is done, you will get a message confirming that the build has been successful: "The build folder is ready to be deployed".

 

3.4 Manually copy the /build files and paste in the server repo

Select all the files that have been created in that /build folder (without the /build folder though, only the files inside), and copy them. We are going to move them to the backend, because they need to be served from the server for the deploy.

In your SERVER/BACKEND code, open the /public folder and delete everything that is inside. If you don't have that /public folder, you will have to create it in your root folder.

Paste all the files you copied from the /build folder in the frontend to this /public folder in the backend.

   

4. CONFIGURATION IN THE SERVER

4.1. In App.js, make sure you have this middleware

app.use(express.static(path.join(__dirname, "public")));

 

4.2. In App.js, add the route for serving React App

After all your routes, but before the error handler, include that snippet of code:

// ROUTE FOR SERVING REACT APP (index.html)
app.use((req, res) => {
  // If no routes match, send them the React HTML.
  res.sendFile(__dirname + "/public/index.html");
});

 

4.3. In your SERVER code

Make sure you have this env variable setup for your database: MONGODB_URI If not, create it in the .env file and replace the mongo db address by this variable everywhere

 

4.4. In App.js, configure CORS to allow requests coming from the Heroku server.

You will need to add an additional string that will have the value of your Heroku app
To get the url of your app, go to the Heroku dashboard and click on the "Open app" top right button (the app is not supposed to be working yet, just copy the full Url of the app that appears in the navbar, as well as the non-secure version of this url (http))

// CORS MIDDLEWARE SETUP
app.use(
  cors({
    credentials: true,
    origin: [process.env.PUBLIC_DOMAIN, 'https://name-of-your-app.herokuapp.com', 'http://name-of-your-app.herokuapp.com'],
  }),
);

Very important: do not add any slash at the end of that url

 

4.5. In package.json

In your terminal, run: node --version and copy the version number you get.

In package.json, on the bottom after devDependencies (at the end, but still inside the main {}), paste this line by replacing the version number of Node you got.

  "engines": {
    "node": "12.x"
  }

 

4.6. Deploy to heroku

In your SERVER/BACKEND repo, commit your changes and deploy to heroku:

$ git add .
$ git commit -m 'Deploy v.1'
$ git push heroku master

   

5. CREATE A DATABASE IN THE CLOUD WITH MONGO ATLAS

5.1. Register to Mongo Atlas

If you are a brand new user:

  • Signup: Register on MongoDB Atlas
  • Build your first cluster:
    • Select "Create a cluster" (FREE option)
    • Select "AWS" as cloud provider, Europe (Frankfurt) as the region, "Cluster tier" (free) as the solution, and click on "Create cluster"
  • Create your database user:
    • You should have been redirected to the console panel > Select "Database Access" in the left side menu and there > click on "Add new user database"
    • In the section Password authentication, add a username and click on "augogenerate Secure Password" and copy-paste it in a secure place right away (you will need it for later)
    • In the "Database User Privileges", select "Read and write to any database" (give username and pwd)
    • Click on "Create new user"
  • Whitelist your IP address:
    • Go to "Network Access" in the left side menu
    • Once on that page, click on the big "Add IP Address" green button
    • In the pop-up that appears, select "Allow Access From Anywhere" and click "Confirm" (it you already had it setup from before, the IP Address should appear already in the IP Whitelist)
  • Connect to your cluster:
    • Go to "Clusters" in the left side menu: in the sandbox, click on "Connect" and in the pop up that opens, click on "Connect your application" > Select DRIVER: "Node.js" and VERSION: "3.0 or later" > Copy the "connection string" that has been prepared for you

 

5.2. Add the cloud database you just created as a config var in Heroku

Back on Heroku dashboard, go to: "Settings" > "Reveal Config Vars" and:

  • Write "MONGODB_URI" in the KEY field
  • Paste the connection string in the VALUE field, but change the password by yours (the one you created in MongoDB Atlas), as well as a database name
  • Click on the "Add" button to save that config var

If you use a SECRET_SESSION env variable or any other env variable in your SERVER/BACKEND repo, add it under Heroku config vars as well.

   

6. DEBUG DEPLOYMENT

Your app should be working now.
In case it is not, run the following command in your SERVER/BACKEND repo:

$ heroku logs --tail
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment