Introduction

Angular Universal is a technology that allows you to perform server-side rendering (SSR) of your Angular applications. This means that instead of rendering your application entirely in the browser, parts of it can be rendered on the server and then sent to the client. This can significantly improve the performance and SEO of your application.

Key Benefits of Angular Universal:

  • Improved Performance: Faster initial load times as the server sends a fully rendered page to the client.
  • Better SEO: Search engines can crawl the fully rendered HTML, improving the discoverability of your application.
  • Enhanced User Experience: Users see content faster, leading to a better overall experience.

Setting Up Angular Universal

Step 1: Install Angular Universal

First, you need to add Angular Universal to your existing Angular project. You can do this using the Angular CLI.

ng add @nguniversal/express-engine

This command will:

  • Install the necessary packages.
  • Create a server-side app module.
  • Update your angular.json file to include server-side rendering configurations.

Step 2: Update Server Module

The ng add command will create a server.ts file and a main.server.ts file. These files are used to bootstrap your Angular application on the server.

server.ts

import 'zone.js/dist/zone-node';
import { ngExpressEngine } from '@nguniversal/express-engine';
import * as express from 'express';
import { join } from 'path';

import { AppServerModule } from './src/main.server';
import { APP_BASE_HREF } from '@angular/common';
import { existsSync } from 'fs';

const app = express();
const PORT = process.env.PORT || 4000;
const DIST_FOLDER = join(process.cwd(), 'dist/browser');

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

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

// Example Express Rest API endpoints
// app.get('/api/**', (req, res) => { });

// Server static files from /browser
app.get('*.*', express.static(DIST_FOLDER, {
  maxAge: '1y'
}));

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

// Start up the Node server
app.listen(PORT, () => {
  console.log(`Node Express server listening on http://localhost:${PORT}`);
});

Step 3: Build and Serve

To build your application for server-side rendering, you need to run the following command:

npm run build:ssr

This will create a dist folder with two subfolders: browser and server.

To serve your application, run:

npm run serve:ssr

This will start an Express server that serves your Angular application with server-side rendering.

Practical Example

Let's create a simple example to demonstrate how Angular Universal works.

Step 1: Create a New Component

Create a new component called server-info.

ng generate component server-info

Step 2: Update the Component

Update the server-info.component.ts file to display some server-side information.

import { Component, OnInit } from '@angular/core';
import { isPlatformServer } from '@angular/common';
import { PLATFORM_ID, Inject } from '@angular/core';

@Component({
  selector: 'app-server-info',
  templateUrl: './server-info.component.html',
  styleUrls: ['./server-info.component.css']
})
export class ServerInfoComponent implements OnInit {
  isServer: boolean;

  constructor(@Inject(PLATFORM_ID) private platformId: Object) { }

  ngOnInit(): void {
    this.isServer = isPlatformServer(this.platformId);
  }
}

Update the server-info.component.html file to display whether the component is being rendered on the server or the client.

<div>
  <p *ngIf="isServer">This content is rendered on the server.</p>
  <p *ngIf="!isServer">This content is rendered on the client.</p>
</div>

Step 3: Add the Component to App Module

Add the ServerInfoComponent to your AppModule.

import { ServerInfoComponent } from './server-info/server-info.component';

@NgModule({
  declarations: [
    // other components
    ServerInfoComponent
  ],
  // other configurations
})
export class AppModule { }

Step 4: Use the Component in Your Application

Add the ServerInfoComponent to your app.component.html.

<app-server-info></app-server-info>

Step 5: Build and Serve

Build and serve your application again using the following commands:

npm run build:ssr
npm run serve:ssr

Visit http://localhost:4000 to see your application with server-side rendering.

Conclusion

In this section, you learned about Angular Universal and how to set it up in your Angular application. You also created a simple example to demonstrate server-side rendering. By using Angular Universal, you can significantly improve the performance and SEO of your Angular applications, providing a better user experience.

Next, we will dive into performance optimization techniques to further enhance your Angular applications.

© Copyright 2024. All rights reserved