ANGULAR
Complete Angular Tutorial For Beginners Introduction to Angular | What is Angular? Architecture Overview & Concepts of Angular How to Install Angular How to Create a new project in Angular Bootstrapping in Angular: How It Works Internally Angular Components Overview & Examples Data Binding in Angular Interpolation in Angular Property Binding in Angular Event Binding in Angular ngModel & Two way Data binding in Angular NgModelChange & Change Event in Angular Child/Nested Components in Angular angular directives angular ngFor directive ngSwitch, ngSwitchcase, ngSwitchDefa ult Angular Example How to use ngIf, else, then in Angular By example NgClass Example Conditionally apply class Angular ngStyle Directive Angular Trackby to improve ngFor Performance How to Create & Use Custom Directive In Angular Working with Angular Pipes How to Create Custom Pipe in Angular Formatting Dates with Angular Date Pipe Using Angular Async Pipe with ngIf & ngFor angular keyValue pipe Using Angular Pipes in Components or Services Angular Component Communication & Sharing Data Angular Pass data to child component Angular Pass data from Child to parent component Component Life Cycle Hooks in Angular Angular ngOnInit And ngOnDestroy Life Cycle hook Angular ngOnChanges life Cycle Hook Angular ngDoCheck Life Cycle Hook Angular Forms Tutorial: Fundamentals & Concep t s Angular Template-driven forms example How to set value in template-driven forms in Angular Angular Reactive Forms Example Using Angular FormBuilder to build Forms SetValue & PatchValue in Angular StatusChanges in Angular Forms ValueChanges in Angular Forms FormControl in Angular FormGroup in Angular Angular FormArray Example Nested FormArray Example Add Form Fields Dynamically SetValue & PatchValue in FormArray Angular Select Options Example in Angular Introduction to Angular Services Introduction to Angular Dependency Injection Angular Injector, @Injectable & @Inject Angular Providers: useClass, useValue, useFactory & useExisting Injection Token in Angular How Dependency Injection & Resolution Works in Angular Angular Singleton Service ProvidedIn root, any & platform in Angular @Self, @SkipSelf & @Optional Decorators Angular '@Host Decorator in Angular ViewProviders in Angular Angular Reactive Forms Validation Custom Validator in Angular Reactive Form Custom Validator with Parameters in Angular Inject Service Into Validator in Angular template_driven_form_validation_in_angular Custom Validator in Template Driven Forms in Angular Angular Async Validator Example Cross Field or Multi Field Validation Angular How to add Validators Dynamically using SetValidators in Angular Angular HttpClient Tutorial & Example Angular HTTP GET Example using httpclient Angular HTTP POST Example URL Parameters, Query Parameters, httpparams in Angular HttpClient Angular HTTPHeaders Example Understanding HTTP Interceptors in Angular Angular Routing Tutorial with Example Location Strategy in Angular Angular Route Params Angular : Child Routes / Nested Route Query Parameters in Angular Angular Pass Data to Route: Dynamic/Static RouterLink, Navigate & NavigateByUrl to Navigate Routes RouterLinkActive in Angular Angular Router Events ActivatedRoute in Angular Angular Guards Tutorial Angular CanActivate Guard Example Angular CanActivateChild Example Angular CanDeactivate Guard Angular Resolve Guard Introduction to Angular Modules or ngModule Angular Routing between modules Angular Folder Structure Best Practices Guide to Lazy loading in Angular Angular Preloading Strategy Angular CanLoad Guard Example Ng-Content & Content Projection in Angular Angular @input, @output & EventEmitter Template Reference Variable in Angular ng-container in Angular How to use ng-template & TemplateRef in Angular How to Use ngTemplateOutlet in Angular '@Hostbinding and @Hostlistener_in_Angular Understanding ViewChild, ViewChildren &erylist in Angular ElementRef in Angular Renderer2 Example: Manipulating DOM in Angular ContentChild and ContentChildren in Angular AfterViewInit, AfterViewChecked, AfterContentInit & AfterContentChecked in Angular Angular Decorators Observable in Angular using RxJs Create observable from a string, array & object in angular Create Observable from Event using FromEvent in Angular Using Angular observable pipe with example Angular Map Operator: Usage and Examples Filter Operator in Angular Observable Tap operator in Angular observable Using SwitchMap in Angular Using MergeMap in Angular Using concatMap in Angular Using ExhaustMap in Angular Take, TakeUntil, TakeWhile & TakeLast in Angular Observable First, Last & Single Operator in Angular Observable Skip, SkipUntil, SkipWhile & SkipLast Operators in Angular The Scan & Reduce operators in Angular DebounceTime & Debounce in Angular Delay & DelayWhen in Angular Using ThrowError in Angular Observable Using Catcherror Operator in Angular Observable ReTryWhen inReTry, ReTryWhen in Angular Observable Unsubscribing from an Observable in Angular Subjects in Angular ReplaySubject, BehaviorSubject & AsyncSubject in Angular Angular Observable Subject Example Sharing Data Between Components Angular Global CSS styles View Encapsulation in Angular Style binding in Angular Class Binding in Angular Angular Component Styles How to Install & Use Angular FontAwesome How to Add Bootstrap to Angular Angular Location Service: go/back/forward Angular How to use APP_INITIALIZER Angular Runtime Configuration Angular Environment Variables Error Handling in Angular Applications Angular HTTP Error Handling Angular CLI tutorial ng new in Angular CLI How to update Angular to latest version Migrate to Standalone Components in Angular Create Multiple Angular Apps in One Project Set Page Title Using Title Service Angular Example Dynamic Page Title based on Route in Angular Meta service in Angular. Add/Update Meta Tags Example Dynamic Meta Tags in Angular Angular Canonical URL Lazy Load Images in Angular Server Side Rendering Using Angular Universal The requested URL was not found on this server error in Angular Angular Examples & Sample Projects Best Resources to Learn Angular Best Angular Books in 2020

Server Side Rendering Using Angular Universal

This Angular Universal Tutorial explains how to achieve Server Side Rendering using Angular Universal. Server-Side Rendering or SSR is a technique, which renders the pages on the server-side before sending it to the browser. We will learn what is Angular Universal is and the need for server-side rendering. Later we will show you how to create an example angular universal app with server-side rendering. We also discuss the very important things that you should know before you diving into server-side rendering using Angular Universal.

What is Angular Universal

The Angular Universal renders the HTML view of the requested URL at the server, before sending it to the user’s browser. This will make the app load faster and more importantly search engine friendly.

Why Server Side rendering required

The Angular apps are single-page applications. They consist of lots of javascript code. These Javascript codes run on the client’s browser and generate an HTML view on the fly. The app does not send any request to the server when the user navigates from one page to another page. The Browser does all the renderings of the page. App sends requests only for data & static resources like images to the backend. This makes the app work very fast for the user.

But it is search engines who bring users to the site. They assign ranks to each page based on several factors. Speed & Content are the two of the topmost ranking factors. This is where SPA frameworks like Angular suffer.

Speed

The initial loading of the Angular apps is slow because,

  1. It needs to download a lot of JavaScript files
  2. Execute the JavaScript and render the HTML to the view.

Content

To see the content, the search engines need to execute JavaScript. Although FormBuilder Google does a good job of executing the JavaScript and reading the content, you cannot trust it to get it right all the time. The other search engines like bing etc also not able to process it. The social media crawlers like Facebook & twitter do not execute JavaScript, Hence they will not see the content.

We can solve the above problems by rendering the content at the server and send the static HTML to the user.

What is Server-Side Rendering

Server-Side Rendering or SSR is a technique, which executes the javascript and generates the HTML file on the server and sends it to the client-side.

For Example, when the request for a specific page arrives at the server, it locates the index.html. Now instead of sending it to the browser, the server passes it to a renderer process. The Renderer executes the Angular Framework (as if it is running in the browser) and generates the HTML. It also makes HTTP Requests to the backend server if required to get the data. Finally, the server sends the generated HTML to the Browser

The Browser now shows the HTML to the user. At this point the browser is yet to download the Angular, Hence the mouse movements & keyboard events will not have any effect on the page. The page is not yet interactive.

The browser starts to download the Angular framework. Once the Angular loads and bootstraps, it starts to capture the user events. The page becomes interactive. From this point onwards, the Angular takes over & any further navigation happens at client side

Server Side rendering Vs Client-Side Rendering

The following table shows the difference between Server-side rendering Vs Client-Side Rendering.

Sr.No Client-Side Rendering Server Side Rendering
1 User sends the requests for a page User sends the requests for a page
2 Server locate the index.html and sends it to the user Server locate the index.html and sends it to the Renderer Process running in Server
3 Renderer prepares the initial page, by executing the Angular Framework and sends it to the browser Renderer prepares the initial page, by executing the Angular Framework and sends it to the browser
4 The Browser displays the blank page, but there is no content there The browser shows the initial page to the user. The page may be non-interactive at this time.
5 The browser downloads the CSS & JavaScript The browser downloads the CSS & Javascript
6 Browser executes Angular Framework (JavaScript) & Renders the page Browser executes Angular Framework (JavaScript)
7 User sees the Interactive Page The page becomes interactive.

Now, let us see how this solves the problem of Content & Speed

Content and SSR

Since the server generates the content, there is no need for search engines to execute the javascript. The social media crawlers also see the HTML

Speed and SSR

Does it solves the problem of speed?. The short answer is NO.

Implementing SSR does not speed up your site all by itself. Because you are only moving the rendering to the server from the browser. In fact, if the server is busy, it may slow your site down.

But it will improve the first contentful paint or FCP.

But, you get a great speed when you cache the rendered response. Serving the cached response to the user eliminates the rendering process and serves the HTML instantly to the user. This is possible only with the SSR.

Angular Universal Tutorial

Create a new Angular project using the Angular CLI

                              

ng new ssr
                            
                        

Check the app is running by using the command

                              
 
ng serve
                            
                        

Right-click anywhere on the browser windows and view page source. You will see that there is no content. This is what search engines will see when they crawl your site.

                              

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Ssr</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
<script src="runtime.js" type="module"></script><script src="polyfills.js" type="module"></script><script src="styles.js" type="module"></script><script src="vendor.js" type="module"></script><script src="main.js" type="module"></script></body>
</html>
 
                            
                        

Adding Angular Universal

To add Angular Universal to the above project, run the following command. It will add the express-engine to the project. You should specify the name of the project under the flag --clientProject. Name of the project is what you specify while creating the project using ng new <projectName>

                              

ng add @nguniversal/express-engine --clientProject ssr
                            
                        

You can find the project name from the angular.json file from projects node.

                              

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "ssr": {                             ====> Name of the project
      "projectType": "application",
      "schematics": {},
                            
                        

Now, you can run the project by running the following command

                              

npm run build:ssr && npm run serve:ssr
 
                            
                        
image
Compiling Angular Universal App

Things to Note

No Hash Location Strategy

If you are still using HashLocationStrategy (where URL looks like http://localhost:4200/#/product) then you better move to PathLocationStrategy. They won’t work with Universal Apps.

Browser API Do not work

The objects such as window, location & document, etc work only on the browser. They do not exist on the server. You can make use of Document or Location for those tasks.

If you are manipulating the DOM elements by using the nativeElement of the ElementRef then it will also not work on the server. You can make use of the Renderer2

Find out where you are running server or browser

Sometimes it is necessary to find out whether the code is executing on the server or browser. For instance, you may want to make use of a browser API, which won’t work in the server and may result in an error. The Angular has isPlatformBrowser & isPlatformServer methods from the @angular/common package. You need to inject them using the PLATFORM_ID injection token

The Duplication of HTTP Requests.

Consider the example where your app makes a request to the back end to get some data and displays it to the user.

When the page requests for the data, the server makes the HTTP Request for the data. It waits for the HTTP Request to finish before rendering the page. Then the server sends the page to the browser. The Browser instantly displays the page along with the data.

Now, Browser downloads and bootstraps the Angular framework. The Angular also makes the same HTTP request to get the data, resulting in duplication.

To Mitigate that, you can make use of BrowserTransferStateModule & ServerTransferStateModule.

Make URL’s Absolute

If you are making HTTP requests from the client-side, then ensure that you use absolute URLs. The Requests with Relative URLs fail during the SSR.

HTTP Security

The authenticated HTTP Request for data to the backend server fails in Server. Because the server cannot access the authentication cookies stored in the client. You will have to handle the security at the server-side your self.

Browser Events

SSR Apps sends the rendered HTML to the browser and browser immedialyty displays it. In the backgroud, browser downloads the Angular Framework and then bootstraps it.

In between these two events, the user sees the non-interactive page, because angular is yet to load. The events like clicking on a button or mouse movements are not captured.

You can work around this problem using PreBoot Library It Replays all events once the app becomes interactive. Hence user do not have to perform the actions again

Summary

In this Angular Universal Tutorial, we learned how to implement Server Side Rendering. The SSR is useful when you want your app to be Search engine friendly.