Introduction
Last modified on Fri 17 Mar 2023

A normal Angular application executes in the browser, rendering pages in the DOM in response to user actions. Angular Universal executes on the server, generating static application pages that later get bootstrapped on the client. This means that the application generally renders more quickly, giving users a chance to view the application layout before it becomes fully interactive.

What is Server Side Rendering (SSR)?

Server-side rendering (SSR) is an application’s ability to render HTML content of a single-page-app on the server and serve it to the client. This is in contrast to how regular SPAs without SSR work, where all the HTML is rendered on the client after the JS application is started. With SSR, the web browser submits a request to the server, which responds by sending back a fully rendered page to the client.

Why we use Server Side Rendering (SSR)?

There are 3 main reasons to add SSR to an Angular app:

  1. Search engine optimization (SEO)
  2. Social media link sharing
  3. Improving initial page load performance on all types of devices and networks

Angular Universal

Angular Universal is a tool which allows the server to render Angular application's HTML content. For a detailed guide, please check out the official Angular Universal documentation. We also recommend reading about some of the gotchas.

To add Angular Universal run the following CLI command:

ng add @nguniversal/express-engine

The command creates the following folder structure:

src
|-- index.html                             // <-- app web page
|-- main.ts                                // <-- bootstrapper for client app
|-- main.server.ts                         // <-- * bootstrapper for server app
|-- style.css                              // <-- styles for the app
|-- app/  …                                // <-- application code
|   |-- app.server.module.ts               // <-- * server-side application module
|-- server.ts                              // <-- * express web server
|-- tsconfig.json                          // <-- TypeScript base configuration
|-- tsconfig.app.json                      // <-- TypeScript browser application configuration
|-- tsconfig.server.json                   // <-- * TypeScript server application configuration
|-- tsconfig.spec.json                     // <-- TypeScript tests configuration

The files marked with * are new added files after running the command.

Package.json file configuration

In the package.json file update the following scripts:

{
  "start": "ng run APP_NAME:serve-ssr",
  "build": "ng build && ng run APP_NAME:server",
  "serve": "node dist/APP_NAME/server/main.js"
}

APP_NAME is application name. For example js-infinum-website.

This configuration uses SSR for development as well, not just for production. This helps catch any SSR-specific errors during development. A slight trade-off is that the development server build times are a bit longer.