Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Universal: How to move to production?

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
like image 328
Dzhuneyt Avatar asked Oct 21 '25 16:10

Dzhuneyt


1 Answers

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

like image 88
David Avatar answered Oct 23 '25 05:10

David



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!