Explain Codes LogoExplain Codes Logo

Html5 Local Storage fallback solutions

html
cross-browser-compatibility
local-storage
fallback-solutions
Alex KataevbyAlex KataevΒ·Feb 22, 2025
⚑TLDR

The simplest fallback for Local Storage is to use cookies. Whenever localStorage is unavailable, use cookies to store data. Here is a quick implementation:

function saveData(key, value) { try { localStorage.setItem(key, value); } catch (e) { document.cookie = `${encodeURIComponent(key)}=${encodeURIComponent(value)};path=/`; } // If life hands you errors, make cookies! πŸͺ } function loadData(key) { try { return localStorage.getItem(key); } catch (e) { return document.cookie.split('; ') .map(c => c.split('=')) .find(pair => pair[0] === encodeURIComponent(key))?.[1] || null; } // Cookie, anyone? πŸ•΅οΈ }

This simple escapist approach (encodeURIComponent) ensures a smooth transition between localStorage and cookies. Also, the try...catch means your fallback works gracefully, regardless of the exception thrown.

Using PersistJS for browser compatibility

The presence of localStorage may not always be a guarantee. Cross-browser compatibility necessitates a consistent and effortless fallback solution, which PersistJS offers, supporting storage backends such as localStorage, userData, googlegears, flash, and the good old cookie.

Toggle between storage backends as necessary, keeping your global scope clean, resulting in a more efficient and dynamic fallback solution.

Keeping data fresh with expiration dates

To manage your data more effectively, establish expiration dates. Keep your storage footprint small and guarantee optimal performance with a lifespan for your cookies β€” a feature localStorage does not natively offer. Here's a demo:

function saveDataWithExpiry(key, value, days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); var expires = "expires=" + date.toUTCString(); document.cookie = `${encodeURIComponent(key)}=${encodeURIComponent(value)};${expires};path=/`; // Cookies are great, but remember to eat them before they expire! πŸ‘€ }

Efficient retrieval and deletion

Maneuvering between localStorage and cookies requires efficient retrieval and deletion mechanics. Cautiously clear both localStorage and cookies to prevent mishaps and inconsistency. Remember to use the proper JSON decoding when retrieving stored data.

function deleteData(key) { try { localStorage.removeItem(key); } catch (e) { document.cookie = `${encodeURIComponent(key)}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/`; // Bye-bye cookie, it was nice knowing ya! πŸ‘‹ } }

Tidiness is happiness – Encapsulation of logic

Avoid clutter in the global namespace by encapsulating your fallback logic. Consider using a module or IIFE (Immediately Invoked Function Expression) to keep your namespace tidy:

(function() { // Local Storage methods // Fallback implementations... // This is where the magic happens! 🎩✨ })();

This will produce a clean global scope, keeping your codebase neat and easy to manage.

Broadening fallback options

Could you use more than just cookies? Yes, of course, if permissible, consider also technologies like Flash or even Google Gears. Even more, consider server-side storage, where your server takes over if localStorage were to fail.

Accessible fallback demo

Having a demo link makes your solution more accessible and interactive. This way, users can test your solution, ensuring it's compatible with their existing applications.

When resorting to cookies, be aware of their 4kB limit. Be judicious with the data you store. Use a JSON library to encode/decode your data, helping you to adhere to the browser's cookie limitations.

Comprehensive storage with localForage

For more extensible and resilient storage, guide users towards libraries like localForage. It provides a simple, but powerful API that wraps IndexedDB, Web SQL, or localStorage.

Keeping an eye on storage usage

Equip users with the means to monitor, audit, and modify the stored data. Whether it’s the browser's DevTools or custom tooling, visibility builds confidence in your storage solutions.