Skip to content

API-compatible in-memory implementation of the Web Storage API

License

Notifications You must be signed in to change notification settings

cheapsteak/local-memory-storage

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

local-memory-storage

npm github checks bundle size

An in-memory typescript implementation of the Web Storage API that should be API-compatible with localStorage.

In addition to supporting Web Storage methods (getItem, setItem, removeItem, clear), this library also closely matches localStorage's behaviour for enumerating and serializing its keys and values.

Usage Example

import { memoryStorage } from 'local-memory-storage';

memoryStorage.setItem('abc', 'xyz');

memoryStorage.getItem('abc'); //> 'xyz'

memoryStorage['abc']; //> 'xyz'

Object.keys(memoryStorage); //> ['abc']

JSON.stringify(memoryStorage); //> {"abc":"xyz"}

If separate instances are desired, the base class can imported instead

import { LocalMemoryStorage } from 'local-memory-storage';

const memoryStorage = new LocalMemoryStorage();

Sample usage for conditionally replacing localStorage

import { memoryStorage } from 'localmemorystorage';

const canUseLocalStorage = () => {
  try {
    const testKey = '__test_if_localstorage_is_available__';
    localStorage.setItem(testKey, testKey);
    localStorage.removeItem(testKey);
    return true;
  } catch (e) {
    return false;
  }
};

export const localStorageWithMemoryFallback = canUseLocalStorage()
  ? localStorage
  : memoryStorage;

Motivation

Trying to access localStorage in incognito mode if your app is being embedded can result in this error:

Uncaught SecurityError: Failed to read the 'localStorage' property from 'Window': Access is denied for this document

One way to solve that would be to create a file like the above example to export a localStorageWithMemoryFallback, and set eslint rules to disallow direct usage of localStorage

// eslintrc.js
module.exports = {
  // ...
  rules: {
    // ...
    "no-restricted-globals": [
      {
        name: "localStorage",
        message: "Use `localStorageWithMemoryFallback` instead",
      },
    ],
    "no-restricted-properties": [
      "error",
      {
        object: "window",
        property: "localStorage",
        message: "Use `localStorageWithMemoryFallback` instead",
      },
    ],
  },
};

About

API-compatible in-memory implementation of the Web Storage API

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published