Simplest Angular Deployment

When you are ready to deploy your Angular application to a remote server, you have various options for deployment.

Basic deployment to a remote server

For the simplest 3 steps deployment, create a production build and copy the output directory to a web server and configure the server to redirect requests for missing files to index.html.

This is because, in a single-page application, there is only one path to the entry file. After bootstrapping the application, instead of going to the server to get a new page, you change what the user sees by showing or hiding parts of the screen that correspond to certain components. As users perform application tasks, they need to switch between the different views you define. In this case, the server needs to redirect all traffic to index.html so Angular can take over to handle path on UI.

This otherwise brilliant solution, overly complicates server management, especially when having applications in subfolders. When the location strategy is misconfigured, the app fails to load any sub-routes and the browser console displays 404 - Not Found.  HashLocationStrategy is another strategy which is immune to this subfolder – subroute mismatch.

HashLocationStrategy to The Rescue

HashLocationStrategy is a LocationStrategy used to configure the Location service to represent its state in the hash fragment of the browser’s URL.

To enable HashLocationStrategy in an Angular application we pass {useHash: true} when we are providing our routes with RouterModule, like so:TypeScript

RouterModule.forRoot(routes, {useHash: true})

URL can contain some data prepended with a # character. The # part of the URL is called the hash fragment. However, it has another very important characteristic in that anything past the # in a URL never gets sent to the server. It’s, therefore, an ideal solution for implementing client-side routing:-

  • It’s part of the URL so can be bookmarked and sent to other people.
  • It won’t confuse the server side since the hash fragment is never sent to the server.
  • It can be programmatically changed via JavaScript.

And that’s exactly why, for a number of years, the primary way of implementing client-side routing was via hash fragments. It is possible to remove the last step from the 3 step deployment process this location strategy.

HashLocationStrategy simplifies the server management when an angular app is running from a subfolder. With this strategy turned on, you can simply deploy in 2 steps;

  1. Start with the production build: ng build --prod
  2. Copy everything within the output folder (dist/ by default) to a folder on the server.

This is the simplest production-ready deployment of your application.