Skip to content

Commit

Permalink
fix: add storage availability check for localStorage and sessionStora…
Browse files Browse the repository at this point in the history
…ge with fallback
  • Loading branch information
plevavas committed Oct 16, 2024
1 parent 952f64b commit 193a988
Showing 1 changed file with 31 additions and 2 deletions.
33 changes: 31 additions & 2 deletions packages/core/src/storage/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,41 @@

import { InMemoryStorage } from './InMemoryStorage';

/**
* Checks if Web Storage (localStorage or sessionStorage) is available.
*
* Based on MDN documentation:
* https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API#testing_for_availability
*/
const storageAvailable = (type: 'localStorage' | 'sessionStorage') => {
let storage;

try {
storage = window[type];
const x = '__storage_test__';
storage.setItem(x, x);
storage.removeItem(x);

return true;
} catch (e) {
console.log(e);

return (
e instanceof DOMException &&
e.name === 'QuotaExceededError' &&
// acknowledge QuotaExceededError only if there's something already stored
storage &&
storage.length !== 0
);
}
};

/**
* @internal
* @returns Either a reference to window.localStorage or an in-memory storage as fallback
*/
export const getLocalStorageWithFallback = (): Storage =>
typeof window !== 'undefined' && window.localStorage
storageAvailable('localStorage')
? window.localStorage
: new InMemoryStorage();

Expand All @@ -17,6 +46,6 @@ export const getLocalStorageWithFallback = (): Storage =>
* @returns Either a reference to window.sessionStorage or an in-memory storage as fallback
*/
export const getSessionStorageWithFallback = (): Storage =>
typeof window !== 'undefined' && window.sessionStorage
storageAvailable('sessionStorage')
? window.sessionStorage
: new InMemoryStorage();

0 comments on commit 193a988

Please sign in to comment.