Angular CLI Deployment: Host Your Angular 2 App on Heroku

Ryan Chenkie
Dec 15, 2016 · 8 min read

Get Set Up with Heroku

heroku create

Prepare the Angular App’s package.json File

Building the App

// package.json"scripts": {
// ...
"postinstall": "ng build --aot -prod"
},

Move the @angular/cli Dependency

// package.json"dependencies": {
// ...
"@angular/cli": "1.2.3",
},

Running the Server

// package.json"scripts": {
// ...
"start": "node server.js"
},

Engines

// package.json"engines": {
"node": "6.11.1",
"npm": "3.10.9"
}

Create an Express Server

npm install --save express
// server.jsconst express = require('express');
const app = express();
// Run the app by serving the static files
// in the dist directory
app.use(express.static(__dirname + '/dist'));// Start the app by listening on the default
// Heroku port
app.listen(process.env.PORT || 8080);

Force Redirect to HTTPS

// server.jsconst express = require('express');
const app = express();
// If an incoming request uses
// a protocol other than HTTPS,
// redirect that request to the
// same url but with HTTPS
const forceSSL = function() {
return function (req, res, next) {
if (req.headers['x-forwarded-proto'] !== 'https') {
return res.redirect(
['https://', req.get('Host'), req.url].join('')
);
}
next();
}
}
// Instruct the app
// to use the forceSSL
// middleware
app.use(forceSSL());// ...

Handle PathLocationStrategy Routing

// server.jsconst path = require('path');// ...// For all GET requests, send back index.html
// so that PathLocationStrategy can be used
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname + '/dist/index.html'));
});

Push to Heroku to Deploy the App

git add .
git commit -m "first deploy"
git push heroku master

Bonus: Create a Script to Handle the Deploy

// package.json"scripts": {
// ...
"deploy": "git push origin master && git push heroku master"
},
npm run deploy

Wrapping Up

Drop Me a Line

Ryan Chenkie

Written by

Mostly JavaScripting with Angular and Node. Screencasting at https://angularcasts.io , Google Developer Expert. Formerly at @auth0.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade