BP163: Use Angular Universal for server-side rendering to improve initial load time and SEO

Angular Universal is a framework for server-side rendering (SSR) of Angular applications. It allows the application to be rendered on the server before being sent to the client, which can significantly improve the initial load time of the application. This is because the client receives a fully rendered HTML page, rather than an empty page that needs to be populated with data from the server.

In addition to improving initial load time, SSR can also improve the search engine optimization (SEO) of the application. Search engines typically have difficulty indexing single-page applications (SPAs) because they rely heavily on JavaScript to render content. By using SSR, the application can provide search engines with a fully rendered HTML page, which can improve its visibility in search results.

To implement Angular Universal, you need to install the @nguniversal packages and configure your application to use them. You also need to create a server-side entry point for your application and modify your application to use platform-server instead of platform-browser. Once you have done this, you can build and deploy your application as usual, and it will be rendered on the server before being sent to the client.

npm install @nguniversal/express-engine @nguniversal/module-map-ngfactory-loader express --save

// server.ts
import 'zone.js/dist/zone-node';
import 'reflect-metadata';

import { enableProdMode } from '@angular/core';

import * as express from 'express';
import { join } from 'path';

import { ngExpressEngine } from '@nguniversal/express-engine';
import { provideModuleMap } from '@nguniversal/module-map-ngfactory-loader';

import { AppServerModule } from './src/main.server';

enableProdMode();

const app = express();

const DIST_FOLDER = join(process.cwd(), 'dist');

const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require('./dist/server/main');

app.engine('html', ngExpressEngine({
  bootstrap: AppServerModuleNgFactory,
  providers: [
    provideModuleMap(LAZY_MODULE_MAP)
  ]
}));

app.set('view engine', 'html');
app.set('views', join(DIST_FOLDER, 'browser'));

app.get('*.*', express.static(join(DIST_FOLDER, 'browser')));

app.get('*', (req, res) => {
  res.render('index', { req });
});

app.listen(4000, () => {
  console.log(`Node server listening on http://localhost:4000`);
});

Download Better Coder application to your phone and get unlimited access to the collection of enterprise best practices.

Get it on Google Play