This article speaks about an interesting side-effect of mixing angular universal with progressive web application (pwa) - and that's a massive performance boost!
The Setup
--
Let's start by creating a standard angular-cli application (v12.1.0 in my case). I enable SSR (angular universal) on that.
ng add @nguniversal/express-engine
Once this is done, let's quickly check if SSR is working as per our expectation.
npm run build:ssr && npm run serve:ssr
Node server fires up on port 4000
and I check for my webpage's source.
view-source:http://localhost:4000/
Wonderful! Nothing fancy so far, and everything works great! CLI application works and universal works.
The next step is to add PWA support.
ng add @angular/pwa
No extra configurations so far, and that's how it will be. Let's build our universal application once again and serve it on localhost:4000
.
But wait!!!
Now when I view my webpage source on the browser, I get this:
So does this mean that my SSR is broken?
The answer is Nope! My SSR is perfectly fine :-) Let's run a quick check to prove this. Open up POSTMAN and run a GET
request against http://localhost:4000
. And voila! I see my server-side-rendered page once again!
So what is happening here?
The conclusion and explanation
--
The reason why we do not see the server-rendered content on the browser source is that, the index.html
is now cached by service-worker at the browser. The browser does not need to wait for the server to render the content any more, and it simply serves the cached version, and Angular takes over thereafter, like a normal SPA. Open up ngsw-config.json
and verify that index.html
is one of the cached resources.
The search-engines/crawlers, on the other hand, would see your website just the way POSTMAN sees it, and will continue to have the entire generated HTML for search-engine-optimization. So this way, you gain the performance boost via service-worker caching, without losing the advantages of angular universal!
Note (and a small exercise): If you remove index.html
from ngsw-config.json
and re-build your universal, you would see that the server-rendered content is back on your browser source, since the HTML is now no longer being cached!
Cheers -:)
Anirban Mukherjee
Top comments (0)