{ "id": "guide/universal", "title": "Server-side rendering (SSR) with Angular Universal", "contents": "\n\n\n
\n mode_edit\n
\n\n\n
\n

Server-side rendering (SSR) with Angular Universallink

\n

This guide describes Angular Universal, a technology that renders Angular applications on the server.

\n

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

\n

For a more detailed look at different techniques and concepts surrounding SSR, please check out this\narticle.

\n

You can easily prepare an app for server-side rendering using the Angular CLI.\nThe CLI schematic @nguniversal/express-engine performs the required steps, as described below.

\n
\n

Note: Download the finished sample code,\nwhich runs in a Node.jsĀ® Express server.

\n
\n\n

Universal tutoriallink

\n

The Tour of Heroes tutorial is the foundation for this walkthrough.

\n

In this example, the Angular CLI compiles and bundles the Universal version of the app with the\nAhead-of-Time (AOT) compiler.\nA Node.js Express web server compiles HTML pages with Universal based on client requests.

\n

To create the server-side app module, app.server.module.ts, run the following CLI command.

\n\n\nng add @nguniversal/express-engine\n\n\n

The command creates the following folder structure.

\n\nsrc/\n index.html app web page\n main.ts bootstrapper for client app\n main.server.ts * bootstrapper for server app\n style.css styles for the app\n app/ ... application code\n app.server.module.ts * server-side application module\nserver.ts * express web server\ntsconfig.json TypeScript base configuration\ntsconfig.app.json TypeScript browser application configuration\ntsconfig.server.json TypeScript server application configuration\ntsconfig.spec.json TypeScript tests configuration\n\n

The files marked with * are new and not in the original tutorial sample.

\n

Universal in actionlink

\n

To start rendering your app with Universal on your local system, use the following command.

\n\nnpm run dev:ssr\n\n

Open a browser and navigate to http://localhost:4200/.\nYou should see the familiar Tour of Heroes dashboard page.

\n

Navigation via routerLinks works correctly because they use the native anchor (<a>) tags.\nYou can go from the Dashboard to the Heroes page and back.\nYou can click a hero on the Dashboard page to display its Details page.

\n

If you throttle your network speed so that the client-side scripts take longer to download (instructions below),\nyou'll notice:

\n\n

User events other than routerLink clicks aren't supported.\nYou must wait for the full client app to bootstrap and run, or buffer the events using libraries like\npreboot, which allow you to replay these events once the client-side scripts load.

\n

The transition from the server-rendered app to the client app happens quickly on a development machine, but you should\nalways test your apps in real-world scenarios.

\n

You can simulate a slower network to see the transition more clearly as follows:

\n
    \n
  1. Open the Chrome Dev Tools and go to the Network tab.
  2. \n
  3. Find the Network Throttling\ndropdown on the far right of the menu bar.
  4. \n
  5. Try one of the \"3G\" speeds.
  6. \n
\n

The server-rendered app still launches quickly but the full client app may take seconds to load.

\n\n

Why use server-side rendering?link

\n

There are three main reasons to create a Universal version of your app.

\n
    \n
  1. Facilitate web crawlers through search engine optimization (SEO)
  2. \n
  3. Improve performance on mobile and low-powered devices
  4. \n
  5. Show the first page quickly with a first-contentful paint (FCP)
  6. \n
\n\n\n

Facilitate web crawlers (SEO)link

\n

Google, Bing, Facebook, Twitter, and other social media sites rely on web crawlers to index your application content and\nmake that content searchable on the web.\nThese web crawlers may be unable to navigate and index your highly interactive Angular application as a human user could do.

\n

Angular Universal can generate a static version of your app that is easily searchable, linkable, and navigable without JavaScript.\nUniversal also makes a site preview available since each URL returns a fully rendered page.

\n\n

Improve performance on mobile and low-powered deviceslink

\n

Some devices don't support JavaScript or execute JavaScript so poorly that the user experience is unacceptable.\nFor these cases, you may require a server-rendered, no-JavaScript version of the app.\nThis version, however limited, may be the only practical alternative for\npeople who otherwise couldn't use the app at all.

\n\n

Show the first page quicklylink

\n

Displaying the first page quickly can be critical for user engagement.\nPages that load faster perform better, even with changes as small as 100ms.\nYour app may have to launch faster to engage these users before they decide to do something else.

\n

With Angular Universal, you can generate landing pages for the app that look like the complete app.\nThe pages are pure HTML, and can display even if JavaScript is disabled.\nThe pages don't handle browser events, but they do support navigation through the site using routerLink.

\n

In practice, you'll serve a static version of the landing page to hold the user's attention.\nAt the same time, you'll load the full Angular app behind it.\nThe user perceives near-instant performance from the landing page\nand gets the full interactive experience after the full app loads.

\n\n

Universal web serverslink

\n

A Universal web server responds to application page requests with static HTML rendered by the Universal template engine.\nThe server receives and responds to HTTP requests from clients (usually browsers), and serves static assets such as scripts, CSS, and images.\nIt may respond to data requests, either directly or as a proxy to a separate data server.

\n

The sample web server for this guide is based on the popular Express framework.

\n
\n

Note: Any web server technology can serve a Universal app as long as it can call Universal's renderModule() function.\nThe principles and decision points discussed here apply to any web server technology.

\n
\n

Universal applications use the Angular platform-server package (as opposed to platform-browser), which provides\nserver implementations of the DOM, XMLHttpRequest, and other low-level features that don't rely on a browser.

\n

The server (Node.js Express in this guide's example)\npasses client requests for application pages to the NgUniversal ngExpressEngine. Under the hood, this\ncalls Universal's renderModule() function, while providing caching and other helpful utilities.

\n

The renderModule() function takes as inputs a template HTML page (usually index.html),\nan Angular module containing components, and a route that determines which components to display.\nThe route comes from the client's request to the server.

\n

Each request results in the appropriate view for the requested route.\nThe renderModule() function renders the view within the <app> tag of the template,\ncreating a finished HTML page for the client.

\n

Finally, the server returns the rendered page to the client.

\n

Working around the browser APIslink

\n

Because a Universal app doesn't execute in the browser, some of the browser APIs and capabilities may be missing on the server.

\n

For example, server-side applications can't reference browser-only global objects such as window, document, navigator, or location.

\n

Angular provides some injectable abstractions over these objects, such as Location\nor DOCUMENT; it may substitute adequately for these APIs.\nIf Angular doesn't provide it, it's possible to write new abstractions that delegate to the browser APIs while in the browser\nand to an alternative implementation while on the server (aka shimming).

\n

Similarly, without mouse or keyboard events, a server-side app can't rely on a user clicking a button to show a component.\nThe app must determine what to render based solely on the incoming client request.\nThis is a good argument for making the app routable.

\n\n

Universal template enginelink

\n

The important bit in the server.ts file is the ngExpressEngine() function.

\n\n// Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)\nserver.engine('html', ngExpressEngine({\n bootstrap: AppServerModule,\n}));\n\n\n

The ngExpressEngine() function is a wrapper around Universal's renderModule() function which turns a client's\nrequests into server-rendered HTML pages. It accepts an object with the following properties:

\n\n

The ngExpressEngine() function returns a Promise callback that resolves to the rendered page.\nIt's up to the engine to decide what to do with that page.\nThis engine's Promise callback returns the rendered page to the web server,\nwhich then forwards it to the client in the HTTP response.

\n
\n

Note: These wrappers help hide the complexity of the renderModule() function. There are more wrappers\nfor different backend technologies at the Universal repository.

\n
\n

Filtering request URLslink

\n

NOTE: The basic behavior described below is handled automatically when using the NgUniversal Express schematic. This\nis helpful when trying to understand the underlying behavior or replicate it without using the schematic.

\n

The web server must distinguish app page requests from other kinds of requests.

\n

It's not as simple as intercepting a request to the root address /.\nThe browser could ask for one of the application routes such as /dashboard, /heroes, or /detail:12.\nIn fact, if the app were only rendered by the server, every app link clicked would arrive at the server\nas a navigation URL intended for the router.

\n

Fortunately, application routes have something in common: their URLs lack file extensions.\n(Data requests also lack extensions but they're easy to recognize because they always begin with /api.)\nAll static asset requests have a file extension (such as main.js or /node_modules/zone.js/bundles/zone.umd.js).

\n

Because we use routing, we can easily recognize the three types of requests and handle them differently.

\n
    \n
  1. Data request: request URL that begins /api.
  2. \n
  3. App navigation: request URL with no file extension.
  4. \n
  5. Static asset: all other requests.
  6. \n
\n

A Node.js Express server is a pipeline of middleware that filters and processes requests one after the other.\nYou configure the Node.js Express server pipeline with calls to server.get() like this one for data requests.

\n\n// TODO: implement data requests securely\nserver.get('/api/**', (req, res) => {\n res.status(404).send('data requests are not yet supported');\n});\n\n\n
\n

Note: This sample server doesn't handle data requests.

\n

The tutorial's \"in-memory web API\" module, a demo and development tool, intercepts all HTTP calls and\nsimulates the behavior of a remote data server.\nIn practice, you would remove that module and register your web API middleware on the server here.

\n
\n

The following code filters for request URLs with no extensions and treats them as navigation requests.

\n\n// All regular routes use the Universal engine\nserver.get('*', (req, res) => {\n res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });\n});\n\n\n

Serving static files safelylink

\n

A single server.use() treats all other URLs as requests for static assets\nsuch as JavaScript, image, and style files.

\n

To ensure that clients can only download the files that they are permitted to see, put all client-facing asset files in\nthe /dist folder and only honor requests for files from the /dist folder.

\n

The following Node.js Express code routes all remaining requests to /dist, and returns a 404 - NOT FOUND error if the\nfile isn't found.

\n\n// Serve static files from /browser\nserver.get('*.*', express.static(distFolder, {\n maxAge: '1y'\n}));\n\n\n

Using absolute URLs for HTTP (data) requests on the serverlink

\n

The tutorial's HeroService and HeroSearchService delegate to the Angular HttpClient module to fetch application data.\nThese services send requests to relative URLs such as api/heroes.\nIn a server-side rendered app, HTTP URLs must be absolute (for example, https://my-server.com/api/heroes).\nThis means that the URLs must be somehow converted to absolute when running on the server and be left relative when running in the browser.

\n

If you are using one of the @nguniversal/*-engine packages (such as @nguniversal/express-engine), this is taken care for you automatically.\nYou don't need to do anything to make relative URLs work on the server.

\n

If, for some reason, you are not using an @nguniversal/*-engine package, you may need to handle it yourself.

\n

The recommended solution is to pass the full request URL to the options argument of renderModule() or renderModuleFactory() (depending on what you use to render AppServerModule on the server).\nThis option is the least intrusive as it does not require any changes to the app.\nHere, \"request URL\" refers to the URL of the request as a response to which the app is being rendered on the server.\nFor example, if the client requested https://my-server.com/dashboard and you are rendering the app on the server to respond to that request, options.url should be set to https://my-server.com/dashboard.

\n

Now, on every HTTP request made as part of rendering the app on the server, Angular can correctly resolve the request URL to an absolute URL, using the provided options.url.

\n\n \n
\n\n\n" }