2
votes

I have just started exploring Angular Universal and Server Side Rendering. I have an existing project, which I kind of got running using Angular Universal's guide.

However, what the documentation doesn't make clear is, how do I apply this to production?


  • Do I need 2 separate builds, one for the browser and one that is served by the NodeJS/Express app?
  • Do I need something (like NGINX) that stands as a load balancer and forwards the requests to either Build 1 or Build 2?
  • Generally, my question is: how do I take an Angular app to production after I've successfully followed Angular Universal's guide?

Currently, after all build commands, I end up with a /dist folder that looks like this:

  • /dist/browser/ (contains the index.html file)
  • /dist/server/ (contains just main.js)
  • /dist/server.js
2

2 Answers

3
votes

When a request hits the backend server (/dist/server.js), the server will render the page html using the server bundle (dist/server/main.js). The page will contain generated html and inlined css for a fast display on the browser. After that, the browser will also download the client bundle (dist/browser/*) and execute it.

The universal server should not be exposed directly; you can use nginx to forward the requests. Here is a basic config sample

server {
    listen 80;
    #...
    root /project/dist/browser;

    location / {
        index index.html;
        #Tries static files, otherwise transfers the request to the nodejs server
        try_files $uri  @universal;
    }


    location @universal {
        #port defined in your server.js
        proxy_pass http://localhost:4000; 
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;

    }

To run the nodeJS server in production, it is advised to use pm2 as indicated by Louis R. If you just want to test the principle, just run node dist/server.js

1
votes

With Universal, client and server application work together.

Basically you can split your requests in two type :

  • Some are required to load the page (before ngOnInit), theses requests need to be executed by the server app to render your dynamic html.

  • The others requests don't need to be run by the server, it should be done by the client app.

To handle that, you should use the transferState, to avoid running two times the same request.

https://angular.io/api/platform-browser/TransferState

To deploy your app you will ofc need Nginx or Apache, pointing on the port used in you server.ts. To serve your application, you just launch your node server (express is used in the angular documentation), with pm2 for example to manage your server :

http://pm2.keymetrics.io/