Subject
- #Web Caching
- #Browser Caching
- #API Caching
- #Nuxt Caching
- #axios interceptor
Created: 2024-09-29
Created: 2024-09-29 21:03
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 store, after clicking on a product from the search results, and then pressing the back button,
the page will re-search.
Reloading an already loaded page is not only bad for UX but also poses significant systemic problems.
Reloading the page unnecessarily calls APIs and increases traffic.
This can lead to cost issues, and if data is being collected on that page, it can also lead to over-collection of specific data.
To solve this, caching pages or API results can be very effective.
- 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 depending on the browser, but it's around 50mb. It can also be used offline.
If you're using axios, you can utilize its built-in interceptor. For identical requests, it returns the response without sending it to the server.
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 method using 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, caching can prevent immediate application of changes 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 use AWS CloudFront to invalidate the cache.
There's also a method of storing the Nuxt server-rendered page itself in the memory cache.
This is server-side caching, caching not just APIs but the entire page. This means it loads instantly when the back button is pressed. Performance is excellent, but be mindful of server memory usage.
If 10,000 users request the same page,
The first user's request renders the page and caches it.
The subsequent 9,999 users accessing the same page receive the cached result.
-> This method is not suitable if you need to display personalized data for each user.
+ Internally, cache uses the lru-cache package.
* lru: Least Recently Used caching algorithm prioritizes removal of the least recently used data.
It uses a hash map or doubly linked list data structure to quickly locate key-value pairs: O(1) time complexity.
Comments0