Angular Universal Production Build Process

Viewed 2443

I'm using Angular Universal 10 and I want to prerender my site.

I'm confused on the proper build process for a production environment.

Angular gives these two commands:

"build:ssr": "ng build --prod && ng run my-app.spa:server:production",
"prerender": "ng run my-app.spa:prerender"

Is it enough to just do this to get a production ready output?

npm run prerender

Or do I need to run both of these?

npm run build:ssr
npm run prerender

What's the difference?

1 Answers

To understand the difference between these two commands, run one and look at the compiled output.

The first command npm run build:ssr will compile your site into a file that can be served using a NodeJS Express app, as you see in server.ts. This way you will still only have one index.html file, but depending on your route, universal will deliver a rendered html file for that route to the browser. So, you are rendering on the server, server-side rendering.

The second command npm run prerender will use the server.ts to "pre-render" each of the routes with their own individual index.html file, all placed in a directory structure according to your routes. The compiled code looks like a traditional static website. So, you are rendering before you deploy, pre-rendering.

So which is best for you?

build:ssr

  • advantage: You don't need to redeploy if content is created dynamically
  • disadvantage: server has to be running a reliable and fast NodeJS process at all times. The good news is there are lots of ways to do this, e.g., serverless functions, app engine, etc.

prerender

  • advantage: your app can be hosted on a regular http server
  • disadvantage: you will probably need to redeploy when new content pages are added

This post on Medium has a pretty good overview with more detailed information.

Related