Angular Server Side Rendering State Transfer For HTTP Requests

This tutorial extends the SSR explained on Server-side rendering (SSR) with Angular Universal page. This tutorial fixes the content flash occurs on SSR write after page loads due to content refresh caused by data received through network requests. If you are crazy about PageSpeed/Web Vitals score as much as me, this will help you to improve:

  1. Largest Contentful Paint (LCP)
  2. First Input Delay (FID)
  3. Cumulative Layout Shift (CLS)

I have tested this on Angular 9 and 10.

Before continuing, please make sure you have SSR set up as mentioned on angular.io. Our goal is to store data received from SSR and reuse them without making any network requests.

  1. Create a HttpInterceptor to intercept SSR HTP requests and store results on TransferState service
  2. Add interceptor to the app.server.module.ts*
  3. Create a HttpInterceptor to intercept HTP requests happen on the client-side and return result from state service instead of making a network request
  4. Add interceptor to the app.module.ts*

*app.module is the module where you put modules required to render things on the browser. app.server.module is where you put things required for the rendering page on the server.

Step 1: Interceptor for SSR to cache HTTP requests

import { HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { makeStateKey, TransferState } from '@angular/platform-browser';
import { tap } from 'rxjs/operators';

@Injectable()
export class ServerStateInterceptor implements HttpInterceptor {

    constructor(private transferState: TransferState) { }

    intercept(req: HttpRequest<any>, next: HttpHandler) {
        return next.handle(req).pipe(
            tap(event => {
                if ((event instanceof HttpResponse && (event.status === 200 || event.status === 202))) {
                    this.transferState.set(makeStateKey(req.url), event.body);
                }
            }),
        );
    }
}

Here the transferState is the service that has the data store. This data store is serialized and passed to the client-side with the rendered page.

intercept()is the method we have to implement from HttpInterceptor interface.

Angular renderer waits for your asynchronous task to be executed before generating the HTML page. After we add this interceptor to the server module, all the HTTP requests you do will go through this interceptor. On the above example, I save all the successful HttpResponses on to the state store.

#angular #server-side-rendering #web-development #seo-optimization #pagespeed #caching #angular-development #angular-application

What is GEEK

Buddha Community

Angular Server Side Rendering State Transfer For HTTP Requests

Angular Server Side Rendering State Transfer For HTTP Requests

This tutorial extends the SSR explained on Server-side rendering (SSR) with Angular Universal page. This tutorial fixes the content flash occurs on SSR write after page loads due to content refresh caused by data received through network requests. If you are crazy about PageSpeed/Web Vitals score as much as me, this will help you to improve:

  1. Largest Contentful Paint (LCP)
  2. First Input Delay (FID)
  3. Cumulative Layout Shift (CLS)

I have tested this on Angular 9 and 10.

Before continuing, please make sure you have SSR set up as mentioned on angular.io. Our goal is to store data received from SSR and reuse them without making any network requests.

  1. Create a HttpInterceptor to intercept SSR HTP requests and store results on TransferState service
  2. Add interceptor to the app.server.module.ts*
  3. Create a HttpInterceptor to intercept HTP requests happen on the client-side and return result from state service instead of making a network request
  4. Add interceptor to the app.module.ts*

*app.module is the module where you put modules required to render things on the browser. app.server.module is where you put things required for the rendering page on the server.

Step 1: Interceptor for SSR to cache HTTP requests

import { HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { makeStateKey, TransferState } from '@angular/platform-browser';
import { tap } from 'rxjs/operators';

@Injectable()
export class ServerStateInterceptor implements HttpInterceptor {

    constructor(private transferState: TransferState) { }

    intercept(req: HttpRequest<any>, next: HttpHandler) {
        return next.handle(req).pipe(
            tap(event => {
                if ((event instanceof HttpResponse && (event.status === 200 || event.status === 202))) {
                    this.transferState.set(makeStateKey(req.url), event.body);
                }
            }),
        );
    }
}

Here the transferState is the service that has the data store. This data store is serialized and passed to the client-side with the rendered page.

intercept()is the method we have to implement from HttpInterceptor interface.

Angular renderer waits for your asynchronous task to be executed before generating the HTML page. After we add this interceptor to the server module, all the HTTP requests you do will go through this interceptor. On the above example, I save all the successful HttpResponses on to the state store.

#angular #server-side-rendering #web-development #seo-optimization #pagespeed #caching #angular-development #angular-application

Seamus  Quitzon

Seamus Quitzon

1595066520

Server Side Rendering (SSR) in Angular 5+ | The simplest and quickest SSR approach

Most of web applications out there are Client Side Rendered, that means all the necessary codes (HTML, CSS, JavaScript) are bundled together and shipped to the client browser at once. Depending on browser URL, frameworks like Angular, React, Vue etc. uses that code to show different views by manipulate DOM and making network requests. This drastically improves user experience but at some cost.

With above approach, user has to wait for a long time before all the necessary files are downloaded, which consists of framework code and application code. Until those files are downloaded, user is forced to see a blank page. Since, all the meaningful views are generated on client side, search engine and social media bots which do not have capability of executing JavaScript, only gets blank index.html page, hence no search engine indexing and social snippet previews. To resolve these problems, we need to render HTML code on the server when user or bots make a request for a page.

In Angular, basically index.html page is served from express server for all the URL paths and that index.html page is passed through some express view engine which injects HTML into <app-root></app-root>, based on current route and component for that route.

So in this article, I will explain step by step implementation of server side rendering with some examples. Make sure you have Angular CLI 1.6+ version installed. If you are creating new angular application, then better install new version of Angular CLI with following command

npm install -g @angular/cli@latest

First, we need to create a angular app with routing. Routing is not necessary, but just to show you how server side rendering works for different URLs, we are going to import a routing module. To create a angular app with routing module automatically generated and scss style support, use below command.

ng new angular-ssr-example --style scss --routing

This will create angular-ssr-example folder, where our angular code will be located. Let’s open that in VS Code or your favourite code editor.

Let’s understand how server side rendering works in practice. Traditionally, we used to serve entire dist folder (technically, only _index.html_ file from_dist__ folder_) which contains build files of our angular application. But now, we are going to create a express server which serves index.html file from dist-browser folder.

#javascript #server-side-rendering #angular-5 #angular-universal #angular

Christa  Stehr

Christa Stehr

1598940617

Install Angular - Angular Environment Setup Process

Angular is a TypeScript based framework that works in synchronization with HTML, CSS, and JavaScript. To work with angular, domain knowledge of these 3 is required.

  1. Installing Node.js and npm
  2. Installing Angular CLI
  3. Creating workspace
  4. Deploying your First App

In this article, you will get to know about the Angular Environment setup process. After reading this article, you will be able to install, setup, create, and launch your own application in Angular. So let’s start!!!

Angular environment setup

Install Angular in Easy Steps

For Installing Angular on your Machine, there are 2 prerequisites:

  • Node.js
  • npm Package Manager
Node.js

First you need to have Node.js installed as Angular require current, active LTS or maintenance LTS version of Node.js

Download and Install Node.js version suitable for your machine’s operating system.

Npm Package Manager

Angular, Angular CLI and Angular applications are dependent on npm packages. By installing Node.js, you have automatically installed the npm Package manager which will be the base for installing angular in your system. To check the presence of npm client and Angular version check of npm client, run this command:

  1. npm -v

Installing Angular CLI

  • Open Terminal/Command Prompt
  • To install Angular CLI, run the below command:
  1. npm install -g @angular/cli

installing angular CLI

· After executing the command, Angular CLI will get installed within some time. You can check it using the following command

  1. ng --version

Workspace Creation

Now as your Angular CLI is installed, you need to create a workspace to work upon your application. Methods for it are:

  • Using CLI
  • Using Visual Studio Code
1. Using CLI

To create a workspace:

  • Navigate to the desired directory where you want to create your workspace using cd command in the Terminal/Command prompt
  • Then in the directory write this command on your terminal and provide the name of the app which you want to create. In my case I have mentioned DataFlair:
  1. Ng new YourAppName

create angular workspace

  • After running this command, it will prompt you to select from various options about the CSS and other functionalities.

angular CSS options

  • To leave everything to default, simply press the Enter or the Return key.

angular setup

#angular tutorials #angular cli install #angular environment setup #angular version check #download angular #install angular #install angular cli

Angular 10 Universal Server Side Rendering (SSR) CRUD Example

This tutorial divided into several steps:

  • Step #1: Create an Angular Universal Application
  • Step #2: Add Mongoose.js Schema and Router
  • Step #3: Add Angular Routes and Navigation
  • Step #4: Add Angular Service
  • Step #5: Add Angular Material UI/UX for CRUD operation
  • Step #6: Deploy, Run, and Test the Angular Universal SSR on VPS

The Angular Universal application that we will build is a very simple application of create, read, update, delete (CRUD) operation. At the end, we will show you how to deploy it to the VPS.

The following tools, frameworks, libraries, and modules are required for this tutorial:

  1. Node.js
  2. Angular Universal with Express-Engine
  3. MongoDB and Mongoose.js
  4. Angular Material
  5. VPS contains Ubuntu, Nginx, PM2, and MongoDB
  6. Terminal or CMD
  7. IDE or Text Editor (we are using VSCode)

Let’s get started with the main steps!

Step #1: Create an Angular Universal Application

As usual, we will start this tutorial by preparing the environment to create or build an Angular application inside the Node.js ecosystem. First, make sure you have download the latest and recommended Node.js version and can run NPM in the Terminal or CMD. To check the existing Node and NPM, type this command.

node -v
v12.18.0
npm -v
6.14.5

Install or update the latest Angular CLI by type this command.

sudo npm install -g @angular/cli

Next, create a new Angular application by type this command.

ng new angular-ssr

If there are the questions, give them the answers like this.

? Would you like to add Angular routing? Yes
? Which stylesheet format would you like to use? SCSS   [ https://sass-lang.com/
documentation/syntax#scss                ]

Next, go to the newly created Angular 10 application folder then type this command to add Angular Universal SSR.

cd ./angular-ssr
ng add @nguniversal/express-engine --clientProject angular-ssr

Next, check the Angular Universal SSR application by running this application using these commands.

npm run build:ssr && npm run serve:ssr

Open the browser then go to ‘localhost:4000’ and you will this standard Angular welcome page.

Angular 10 Universal Server Side Rendering (SSR) CRUD Example - welcome page

#angular #angular universal server-side rendering #crud

Carmen  Grimes

Carmen Grimes

1594687554

Server-side rendering (SSR) in Angular applications

Server-side rendering and Client-side rendering

Angular applications by default rely on the browser to compile all the code. Even though this is the behavior, there is a way to change this. You can change your application to compile on a server instead of the client’s browser.

This discussion comes down to client-side rendering (CSR) vs server-side rendering (SSR). In this article, I’ll be going over what SSR and CSR are, their pros and cons, and how to convert your application to do SSR.

In simple terms, CSR relies on the client’s browser to compile the code. On the other hand, SSR relies on a server to compile the code which then gets returned already compiled to the client.

It is well known that there is no perfect solution for any problem in software development. As it is with everything else, there are pros and cons to these two options.

Let’s start with an example

First, start by creating an Angular application. You can do this by running the following command ng init my-application.

After this, start your application by running npm run start.

If you open an instance of your terminal and run curl http://localhost:4200, you will end up retrieving something like this.

Image for post

What is wrong with this? Nothing. If you take a look, you will notice that there’s only <app-root> and nothing inside it. But your page does have other contents, correct? Where is the rest?

If you were to go to a browser and access this page, you will see something completely different. As you can see, you do see the contents of your app-root component. This is because the browser was the one that compiled your application.

Image for post

Some developers might leverage Angular’s APIs for SEO optimization too. For example, you could set meta or title tags programmatically. In the following example, you can set the title and a few meta tags for this page.

#server-side-rendering #angular #javascript #programming #software-engineering