Caching web pages and API responses can resolve performance issues and UX degradation caused by unnecessary data requests.
Various caching techniques are available, including browser storage, Axios Interceptor, Nuxt keep-alive, Vuex, and web server caching. Server-side rendering page caching is effective for performance improvement, but memory usage should be considered.
Cache invalidation allows for immediate application of changes when distributing images and other resources.
You've likely experienced this many times: when you hit the back button on a website, the already loaded page reloads.
For example, in an online shopping mall, after clicking on a product from a search result, if you go back,
the search is performed again.
Reloading an already loaded page is not only bad for UX but also creates bigger systemic problems.
Reloading the page leads to unnecessary API calls and increased traffic.
This can lead to cost issues, and if you're collecting data from that page, it can also lead to over-collection of specific data.
Caching pages or API results can significantly improve this.
- localStorage retains data even after closing the browser.
- sessionStorage loses data when the browser or tab is closed.
- IndexedDB is used for storing large amounts of data. It allows asynchronous storage and is NoSQL. It can store images and videos. The maximum capacity varies by browser, but is around 50MB. It can also be used offline.
2. Axios Interceptor
If you use axios, you can utilize its built-in interceptor. For the same request, it returns a response without sending it to the server.
Caching within the Nuxt Framework
Wrapping a component with the keep-alive tag allows you to cache the component.
You can configure whether to call fetch() during server-side rendering. If it's false, fetch is only called on the client side.
There's also a way to utilize Vuex. The principle is the same as browser storage.
You can use a web server (Nginx) to include cache settings in the response header.
However, due to caching, immediate application may not be possible when deploying resources like images. In such cases, you need to invalidate the cache. You can change the filename, add a request to invalidate the cache, or apply cache invalidation if you are using AWS CloudFront.
There's also a way to store Nuxt server-rendered pages themselves in the memory cache.
This is server-side caching, caching not only APIs but the entire page. This means that going back is immediate with no delay. Performance is excellent, but it uses server memory, so be cautious.
If 10,000 users request the same page,
The first user's request renders the page, and it's cached.
The subsequent 9,999 users accessing the same page receive the cached result from the server.
-> This method is not suitable if you need to display individualized data for each user.