Deploy Angular2+ application in Node.js server

In this article we will learn how to deploy a angular application in Node.js server.

I assume you already have an angular application ready and you are familiar with the Angular CLI commands

  • First step is to create a production build of your application using the below command
ng build --prod
  • Second step is to copy all the files within the output folder (dist/ by default) to a folder on the server.

  • Third step is to configure the node js server to redirect requests for missing files to index.html

Node.js server configuration:

var express = require('express');
var compression = require('compression');
var app = express();
var path = require('path');

var port = process.env.PORT || 3000;
app.get('/*', function(req, res) {
  res.setHeader('X-UA-Compatible', 'IE=Edge');
  res.status(200).sendFile(path.join(__dirname + '/index.html'));
app.listen(port, function() {
  console.log('server listening on port ' + port);

The above Node.js code snippet will serve the application and redirects to the index.html file when we request for a deep link url and the angular router will handle the request

Please find the github link for the same with the package.json file.

Why not to serve as a static resource?

Because we use angular router to handle our page requests. So when we serve as a static resource the application will fail when we refresh the page. During page refresh the browser will send a request to the server which doesn't exist and the server will return a 404 not found error.

How to handle this?

Since we use Angular router, we must configure the server to return the index.html page when asked for a file that it does not have.

Read more about angular deployment from the official guide

Learn Something New Everyday,
Connect With The Best Developers!

Sign Up Now!

& 500k+ others use Hashnode actively.

No Comments Yet