reactjsreduxlocal-storagepersistencereact-cookie

Where to store user's sensitive data?


I am developing a web with React, Redux and React-Cookie. In this web i have a login system, in which I send a POST request to my Backend API that will send me back the user's data I need for my components (including it's token for the cookie), and I need this data to be Persistent. Currently I am storing the user data in my store, and the boolean of isAuthenticated in the local storage of the client (which I don't know how insecure is this procedure). Where should I store this data? maybe in a cookie? Also if you have some advice regarding the way i store the authenticated boolean would be really nice as well.


Solution

  • The common practice is to store the user object in the local storage and have another key for the token (or you can embed the token inside the user object).

    There is no need for authenticated boolean, you should check if the user exists in the local storage and if it does then your user is authenticated.

    in your logout function make sure to delete the user key from your local storage so the above check will return false.

    function isAuthenticated() {
     return !!localstorage.getItem('user');
    }
    
    function login(credentials) {
      fetch(....)
      .then(res => res.json())
      .then(({user, token}) => {
        localstorage.setItem('user', {...user, token});
       })
    }
    
    function logout() {
      localstorage.removeItem('user');
    }