Seamus  Quitzon

Seamus Quitzon

1598415480

Server-Side Rendering (SSR) Made Easy With Angular Universal 9+

The Angular team recently, announced a pre-render builder in Angular Universal, in Jan 2020 to be specific. Angular Universal is for server-side rending (SSR); with these new Angular Schematics available in Angular 9+, creating new SSR with Angular Universal or configuring your existing application to SSR is easier than ever. All the configuration can be done with Angular CLI.

What Is Server-Side Rendering (SSR)

The server returns a static web page fully complied with dynamic data ready to display on the browser. The fetching of the dynamic data is done by server-side scripts written by server-side languages. This is how we used to render web pages in the old days (PHP/ Perl/CGI), and it has recently gained traction with technologies, such as React and Express. It is SEO friendly and great for devices with low power.

Server-side and client-side rendering

The server returns a complete static web page with all the elements required to display the browser and the client-side scripts required to make the page dynamic.

What Is Client-Side Rendering (CSR)

The server returns a partial web page with no dynamic data, but it provides the client-side scripts necessary to fetch the data on demand asynchronously.

Server-side vs client-side scripts

The client is responsible for fetching the data upon loading a new page or based on user interaction. There are many Async calls to the server. CSR is not SEO friendly, as the content is always dynamic.

Now, we are going to create a standard Angular app, which, by default, has been programmed for Client-side rendering. Then, using the new Angular Schematic, we are going to configure the application as server-side rendering (SSR).

#tutorial #angular #angular 9 #angular schematic #ssr

What is GEEK

Buddha Community

Server-Side Rendering (SSR) Made Easy With Angular Universal 9+
Seamus  Quitzon

Seamus Quitzon

1598415480

Server-Side Rendering (SSR) Made Easy With Angular Universal 9+

The Angular team recently, announced a pre-render builder in Angular Universal, in Jan 2020 to be specific. Angular Universal is for server-side rending (SSR); with these new Angular Schematics available in Angular 9+, creating new SSR with Angular Universal or configuring your existing application to SSR is easier than ever. All the configuration can be done with Angular CLI.

What Is Server-Side Rendering (SSR)

The server returns a static web page fully complied with dynamic data ready to display on the browser. The fetching of the dynamic data is done by server-side scripts written by server-side languages. This is how we used to render web pages in the old days (PHP/ Perl/CGI), and it has recently gained traction with technologies, such as React and Express. It is SEO friendly and great for devices with low power.

Server-side and client-side rendering

The server returns a complete static web page with all the elements required to display the browser and the client-side scripts required to make the page dynamic.

What Is Client-Side Rendering (CSR)

The server returns a partial web page with no dynamic data, but it provides the client-side scripts necessary to fetch the data on demand asynchronously.

Server-side vs client-side scripts

The client is responsible for fetching the data upon loading a new page or based on user interaction. There are many Async calls to the server. CSR is not SEO friendly, as the content is always dynamic.

Now, we are going to create a standard Angular app, which, by default, has been programmed for Client-side rendering. Then, using the new Angular Schematic, we are going to configure the application as server-side rendering (SSR).

#tutorial #angular #angular 9 #angular schematic #ssr

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

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

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

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