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:
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.
*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.
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