Introduction to Angular Universal

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 Angular applications.

Key Benefits of Angular Universal

  • Improved Performance: By rendering the initial view on the server, the time to first meaningful paint is reduced.
  • Better SEO: Search engines can index the content more effectively since the HTML is fully rendered on the server.
  • Faster Load Times: Users see the content faster, which can improve user experience and engagement.

Setting Up Angular Universal

Step 1: Install Angular Universal

To add Angular Universal to your existing Angular project, you need to install the necessary packages.

ng add @nguniversal/express-engine

This command will:

  • Install the @nguniversal/express-engine package.
  • Update your angular.json file.
  • Create a server-side app module (app.server.module.ts).
  • Create a main server file (main.server.ts).

Step 2: Update Angular Configuration

Ensure that your angular.json file has the appropriate configurations for server-side rendering.

{
  "projects": {
    "your-project-name": {
      "architect": {
        "build": {
          "options": {
            "outputPath": "dist/your-project-name/browser"
          }
        },
        "server": {
          "options": {
            "outputPath": "dist/your-project-name/server"
          }
        }
      }
    }
  }
}

Step 3: Create a Server File

Create a file named server.ts at the root of your project. This file will set up an Express server to handle the server-side rendering.

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/your-project-name/browser');

app.engine('html', ngExpressEngine({
  bootstrap: AppServerModule,
}));

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

app.get('*.*', express.static(DIST_FOLDER, {
  maxAge: '1y'
}));

app.get('*', (req, res) => {
  res.render('index', { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
});

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

Step 4: Build and Serve the Application

Build the application for both the browser and the server.

npm run build:ssr
npm run serve:ssr

The build:ssr script will build both the client and server bundles, and the serve:ssr script will start the Express server.

Practical Example

Example Component

Let's create a simple component to demonstrate server-side rendering.

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

@Component({
  selector: 'app-hello-world',
  template: `<h1>Hello, Angular Universal!</h1>`
})
export class HelloWorldComponent {}

Example Module

Include the component in your app module.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { HelloWorldComponent } from './hello-world.component';

@NgModule({
  declarations: [
    AppComponent,
    HelloWorldComponent
  ],
  imports: [
    BrowserModule.withServerTransition({ appId: 'serverApp' })
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Server-Side Module

Ensure the server-side module is set up correctly.

import { NgModule } from '@angular/core';
import { ServerModule } from '@angular/platform-server';
import { AppModule } from './app.module';
import { AppComponent } from './app.component';

@NgModule({
  imports: [
    AppModule,
    ServerModule,
  ],
  bootstrap: [AppComponent],
})
export class AppServerModule { }

Common Mistakes and Tips

Common Mistakes

  • Forgetting to Install Dependencies: Ensure all necessary packages are installed.
  • Incorrect Configuration: Double-check the angular.json and server.ts configurations.
  • Missing Server-Side Logic: Ensure that server-side logic is correctly implemented to handle requests.

Tips

  • Use Lazy Loading: Optimize performance by lazy loading modules.
  • Cache Static Content: Use caching strategies for static content to improve load times.
  • Monitor Performance: Regularly monitor and optimize the performance of your server-side rendered application.

Conclusion

In this section, you learned about Angular Universal and how to set up server-side rendering for your Angular applications. By following the steps outlined, you can improve the performance, SEO, and user experience of your applications. In the next module, we will explore performance optimization techniques to further enhance your Angular applications.

© Copyright 2024. All rights reserved