Saturday, May 23, 2020

Deploying Angular Express Application


Question For an application with an Angular front-end and Node/Express back-end, should the Express application serve the Angular files, or should the Angular files be served from a different server? Would I need two domains to serve Angular files from a different server?

My Answer Your compiled Angular application is just a set of static files that needs to be downloaded to the browser. So they don't have to be served from an Express/Node application. You could host them on an Amazon S3 bucket for example.

Or, you could use some other server technology like nginx that's efficient at serving static files. You don't need a whole separate domain, just a separate sub-domain (so your API might be at https://api.mydomain.com ("api" subdomain), while your Angular code might be served from https://mydomain.com).

Follow-up Question Thanks for the explanation! What about authentication? Is that done on Angular or Express? What is the best practice for this? If I were to pass back a set of static Angular files, wouldn't I also be passing back to a user who hasn't logged in, the files he is not supposed to see yet? Sorry I am new to this, just trying to figure out how the authentication will work. In Express, I understand how it works, but with Angular and Express together, I feel lost.

My Answer In most cases what you want to protect with authentication are the REST APIs - i.e. the resources/data that are stored in the back-end. So you'd allow anyone to download the Angular app, and it would use "route guards" to locally protect parts of the app that require authentication. It would also provide a sign-in user interface to allow you to authenticate with the back-end. Once you successfully authenticate then the Angular app can start calling back-end APIs providing an authentication token in each call so that each REST API call is individually authenticated.

If you really needed to prevent un-authenticated users from downloading parts of the Angular app then you could use other measures like putting the app behind a VPN, using HTTP authentication to access the static files, or using Angular lazy loaded modules that only get loaded for authenticated users.
(See the Angular CanLoad route guard: https://angular.io/api/router/CanLoad )

Massimiliano Morosinotto, CC-BY-SA 2.0

Post a Comment

Note: Only a member of this blog may post a comment.