Deploy an existing MERN app to Heroku
The easiest way to get an app up and running on a live server in just 5 steps
Before we begin, here is the folder structure we are working with to avoid any confusion.
.
├── _client (React app)
├── _node_modules
├── .env
├── .gitignore
├── index.js (server file)
├── package-lock.json
├── package.json
└── README.md
Now here are the 5 steps:
1. Edit server file.
In index.js, near the top add the following line
app.use(express.static(path.join(__dirname, '/client/build')));
so the server knows where to look for the React app.
Then near the bottom, before app.listen gets called add
app.get("*", (req, res) => { res.sendFile(path.join(__dirname + '/client/build/index.html'))});
to ensure the server responds with that React app to user requests.
Read more at
https://create-react-app.dev/docs/deployment/#serving-apps-with-client-side-routing.
2. Configure scripts.
In package.json, in the “scripts” file add the following script
"heroku-postbuild": "cd client && npm install && npm run build"
so the server can run the React app.
3. Create a Heroku application.
Make sure the project contains a Git repository by looking for a .git folder.
If not, initialize a Git repository in the root directory by running
$ git init
$ git add .
$ git commit -m "initial commit"
Ensure that worked by running
$ git status
On branch master
Your branch is up to date with 'origin/master'.nothing to commit, working tree clean // SUCCESS!
Then create a Heroku app, using either the dashboard
OR
Heroku CLI by running heroku create HEROKU_APP_NAME
.
Assuming you’ve downloaded and installed the Heroku CLI, run
$ heroku git:remote -a [INSERT APP NAME HERE]
to add a remote where your code will be stored on Heroku.
Ensure that worked by running
$ git remote
heroku // SUCCESS!
origin
Read more at
https://devcenter.heroku.com/articles/git#tracking-your-app-in-git
4. Set config vars.
In development mode, you may have loaded environment variables from a .env file and accessed them using process.env.KEY
.
On Heroku, environment variables are loaded using config vars. Add config vars, using either settings on the dashboard
OR
Heroku CLI by running
$ heroku config:set [INSERT KEY HERE]=[INSERT VALUE HERE]
Ensure that worked by running
$ heroku config
[KEY]: [VALUE]
Read more at
https://devcenter.heroku.com/articles/config-vars
5. Deploy.
Finally, push that baby up and onto Heroku by running
$ git push heroku master
If you ever need to make changes and deploy again, simply run
$ git add .
$ git commit -m "initial commit"
$ git push heroku master
to push the latest version of your code to the server.