Search code examples
javascriptcookieslocal-storagesession-cookiessession-storage

localStorage does not work with user accounts


I'm building an application whereby if a user wishes to add an item to a personal watchlist, they must be logged in. I use localStorage to store this personal watchlist data and to retrieve it. The problem I am having is that if account 'A' adds an item to their watchlist and then logs out and account 'B' then logs in, the previous stored data is returned from account 'A'.

How can I prevent this from happening so that the data is only saved/returned for each particular user account? Should I be using something instead of localStorage like sessionStorage? Any help is appreciated.


Solution

  • I've solved this personally by including an identifier for the user in the local storage key. You'll have an entry per user and do the lookup based on the identifier. Something like:

    localStorage.setItem(`watchlist:${user.id}`, data) // set
    
    const watchlist = localStorage.getItem(`watchlist:${user.id}`) // get
    

    As noted by @AlexB in the comments, be aware that multiple users on the same device will have the local data of any other users in their localStorage, so be sure to consider privacy.