banjocode Deploy Any SPA + Express App to Heroku For Free

Deploy Any SPA + Express App to Heroku For Free

When you have created a full-stack web application (with React, Vue or Angular) and Express, it is quite difficult to host it for free. This guide will help you do that on Heroku

3 min read

Information

Whichever framework you use; React, Vue or Angular, with an Express backend, this guide will cover how you deploy your site for free to Heroku. It was mainly written with React in mind, so “Deploying React + Express to Heroku” would be a more fitting name, but the same principles do apply to the other frameworks as well, as most logic is created within the Express file and package.json file.

Getting started

This guide is divided into 5 steps:

1. Add endpoint for index.html file in Express

Create a wildcard path in Express, pointing all GET-requests to your index.html file. Be sure that it points to the correct folder, like dist, or build.

app.get("*", (req, res) => {
	res.sendFile(path.join(__dirname, "../../dist/index.html"));
});

2. Serve from your correct folder

Include this line to serve from the correct folder.

app.use(express.static("dist"));

3. Add proxy to localhost

If your server, for example, listens to port 5000, make the proxy listen to that port.

Express

server.listen(process.env.PORT || 5000, () => {
	console.log(`Server running on port ${process.env.PORT || 5000}`);
});

package.json

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

4. Add scripts to package.json

Heroku runs some script before deploying your application. The heroku-postbuild runs before anything else, installing all necessary requirements. The build builds the actual application. The start script is what launches the application.

Be aware that your scripts may look different, the naming is the important part.

"scripts": {
        "build": "webpack --mode production",
        "start": "node src/server/index.js",
        "heroku-postbuild": "npm install && npm run build"

5. Deploying to Heroku

Now to the last part, deploying your application to Heroku. We will do it using their CLI which you can read about here.

# remove git build (optional)
$ rm -rf .git

# make new git config
$ git init
$ git add .
$ git commit -m "Initial commit"

# create heroku server
$ heroku create

# add environment variables (optional)
$ heroku config:set VAR1=variable1

# push to server
$ git push heroku master

If you already have a server and need to add that remote instead of creating a new one:

$ heroku git:remote -a <name-of-server>