DEV Community

Cover image for How to host Angular app on Heroku
Ravi Agheda
Ravi Agheda

Posted on • Updated on

How to host Angular app on Heroku

We need an express server to make the Angular app live.

Install express and path.

npm install express path

Create server.js

const express = require('express');
const path = require('path');

const app = express();

app.use(express.static(__dirname + '/dist/<FOLDER_NAME>'));

// Link index.html of build folder with router.
app.get('/*', (req,res,next) => {
    res.sendFile(path.join(__dirname + '/dist/<FOLDER_NAME>/index.html'));
});


app.listen(process.env.PORT || 8000);
Enter fullscreen mode Exit fullscreen mode

Add these lines in package.json

inside scripts

"start": "node server.js",
"heroku-postbuild": "ng build --prod"
Enter fullscreen mode Exit fullscreen mode

Add engines inside package.json

"engines": {
    "node": "14.15.3",
    "npm": "6.14.9"
  },
Enter fullscreen mode Exit fullscreen mode

Add this project to GitHub and connect this repository with your Heroku app.

Click on deploy.

Thanks for reading :)

Top comments (5)

Collapse
 
umbe1987 profile image
umbe1987

Great, thanks! Just one small correction if I may: "res.sendFile(path.join(dirname + '/dist/dictionary/index.html'));" should probably be changed to something like "res.sendFile(path.join(dirname + '/dist//index.html'));".

Collapse
 
theowlsden profile image
Shaquil Maria

You can make it like this too:

app.get('/*', function (req, res) {
    res.sendFile('index.html', { root: 'dist/<project-name>/' }
    );
});
Enter fullscreen mode Exit fullscreen mode
Collapse
 
rishabhsharma333 profile image
RishabhSharma333 • Edited

I was able to deploy my angular app following this post.I would like to further clerify.here Folder_Name is name of folder in your dist folder (this folder will be created while you build locally).While writing engines write the versions of node and npm installed locally on your system.(find it using node --version and npm --version).

Collapse
 
theowlsden profile image
Shaquil Maria

Thanks for this post!

Collapse
 
damienmarchand profile image
Damien Marchand • Edited

I'm not a fan of this way for hosting static files.
I can show you another solution :
dev.to/damienmarchand/angular-on-h...

I hope it will help :)