Search code examples
javascriptreactjstypescriptnext.jslocal-storage

Change the default localStorage structure


I have two different applications, mysite.com/app1 and mysite.com/app2. Both use similar localStorage keys. In browsers, the localStorage is directly under the domain "mysite.com". This causes the localStorage to get overriden when using both applications in different tabs.

Is there a way to differenciate the two localStorages, without using prefix for everytime.

Like can I make the localStorage under mysite.com/app1 and mysite.com/app2 separate?

I used different prefixes while accessing/setting data in localStorage, and that works, but I am looking for a different solution, where I don't have to use custom logic everytime I am interacting with my localStorage.


Solution

  • You can do followings,

    1. You can host two applications same domain but different sub domains

    2. create two functions which is set JSON string to local storage key and get the same string from it.

    Getter

    function getLocalStorage(key){
    
    return JSON.parse(localStorage.get(key))
    
    }
    

    Setter

    function setLocalStorage(key, value){
    
    return localStorage.set(key, JSON.stringify(value))
    
    }
    

    You can just overwrite the setItem and the getItem in the index.js or app.js

    var SetItem = localStorage.setItem; 
    localStorage.setItem = function(key, value){
        SetItem.call(this, `PREFIX::${key}`, value);
    }
    
    var GetItem = localStorage.getItem; 
    localStorage.getItem = function(){
        GetItem.apply(this, arguments);
    }
    
    localStorage.setItem("keyWithoutPrefix", "data")
    console.log(localStorage.getItem("PREFIX::keyWithoutPrefix"))
    

    Also you can overwrite is using Proxy object( this is much safer )

    Storage.prototype.setItem = new Proxy(Storage.prototype.setItem, {
        apply(target, thisArg, argumentList) {
            return Reflect.apply(target, thisArg, argumentList);
        },
    });
    
    Storage.prototype.setItem = new Proxy(Storage.prototype.setItem, {
        apply(target, thisArg, argumentList) {
            return Reflect.apply(target, thisArg, argumentList);
        },
    });
    
    localStorage.setItem("key", "value")
    
    console.log(localStorage.getItem("key"))