Introduction to client-side caching
Important differences vs. server-side caching
- Client-side caching is not secure, no matter what you do. Do not use client-side caching for any sensitive data, or for data that needs to be kept secret.
- Storage limits on client-side caching are a lot smaller (most modern browsers give 5MB or so for local storage, per website).
When to use client-side caching
The main use case for client-side caching is for data that isn't sensitive, that is unlikely to change often, and where you do not want the data fetched from the server every time a user loads a page.
A good example would be a user's customisation settings on a website; they aren't going to change often, you can easily update them in the client-side cache if they are changed by the user, and you would otherwise have to fetch that data from the server every time your user loads a page.
Client-side caching mechanisms
Almost all client-side caching is done via the browser's localStorage and sessionStorage variables. These are provided by the browser, and are broadly similar but have a few differences.
localStorage
Local storage persists until the browser clears it, so it stays between page loads and across tabs for a given website. The limit in Chrome is 5MB per website as of the time of writing.
sessionStorage
Session storage is more short-term, and is only kept for the current tab; when the tab is closed, the sessionStorage is cleared.
Important considerations
When caching data client-side, there are several important things to keep in mind.
Keep it as light as possible
While the limit on the data you can store in local storage isn't exactly small (5MB equates to a lot of text data), it's better to keep as little in it as you need to.
Ensure you never rely on client-side caching for any form of security or authentication
As said earlier, make sure nothing that is either sensitive or security related is ever cached in the client's local or session storage, as it is inherently insecure to do so.
Remember to update it when needed
When caching data client-side, remember that in some areas of your website you will need to refresh or update the cached data so it remains correct.
For instance, if you cache the user's choice of website theme locally but also store their preference in your database somewhere, your form or page that lets the user change their theme needs to both update the database value and the value in your local cache. You can either have a system of forcing a cache refresh in this case (a bit inefficient), or update the cached value directly.