🚀 4238% faster pages: how to cache Angular Universal routes
The problem
Using Angular Universal, every time you load a page the server does execute your Angular app and returns the HTML response. But, for some of your pages, you don't want that to happened on every request.
The solution
Cache. Cache everything, or at least try to so your server doesn't run your Angular app on every request but returns the HTML generated by the cached execution of it. This is especially handy for pages that do not change every minute (landing pages for example).
This is my implementation using the node cache-manager package that allows you to use different cache engines like Redis if you want to:
Let me explain to you a little bit how it works.
We first defined the interface that every configuration of the route we want to cache as:
On our implementation, you can check the cache handling from line 82 onwards. But basically checks an array of RouteCache objects and if the route the client is fetching is on that array it will cache it.
How to use it
On your server.ts, define the list of routes you want to cache
And then tell your server to use the cache engine:
The results
The results of caching the HTML generated by the Angular app are amazing. Performance is 4238% faster in cached pages, from 551ms on the first load to 13ms on the subsequent calls
The full implementation is available on Github: