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

Angular Server Side Rendering State Transfer For HTTP Requests
13.30 GEEK