简体   繁体   中英

React Redux - storing logged in user details

Im confused in the best place to store logged in user details in a React / Redux application so that I would have access to the likes of first name and last name in the header on every route.

I have the user api key (JWT) stored in localStorage, but I see it is bad practice to store the likes of first name, last name, email etc in localStorage, due to XSS vulnerabilities.

I would prefer not to hit an API on every route just to return the same user details.

I tried storing them in a redux store as session.user, which gets unset when I do a page refresh or change the URL manually. (store is maintained when changing the route via redux saga push )

How can I store first name, last name etc to be used across multiple routes and on page refresh?

My advice is when a user logs into your website, create a session identifier for them and store it in a cryptographically signed cookie. Make sure that whatever cookie library your web framework uses is setting the httpOnly cookie flag. This flag makes it impossible for a browser to read any cookies, which is required in order to safely use server-side sessions with cookies. Make sure that your cookie library also sets the SameSite=strict cookie flag (to prevent CSRF attacks), as well as the secure=true flag (to ensure cookies can only be set over an encrypted connection). Each time a user makes a request to your site, use their session ID (extracted from the cookie they send to you) to retrieve their account details from either a database or a cache (depending on how large your website is)

Redux will store data in the browser memory, it will be lost if you do a full refresh.

If you want to persist your data even after a refresh, you can persist the redux store to the browser session storage https://github.com/ilyagelman/redux-sessionstorage

Otherwise you can save the data you want available in all pages in the session storage without going through redux.

Without actually storing this info in localstoarge there is only one way I can think of achieving this. Your top level component, will re-mount every time the browser refreshes, so in that component's did mount you can fire off a request to get this info from the server and have it stored in your redux store.

Redux global state gets initialized on page refresh. You need to save userDetails in localStorage so it will available across all routes even after refreshing the page. this is how you can do this:

Set localstorage:

 const userDetails = {userName: "foo", pass: "bar"}
 localStorage.setItem('userDetails', JSON.stringify(userDetails));

Access userDetails from localStorage:

const userDetils = JSON.parse(localStorage.getItem( 'userDetails'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM