What is the best way to manage a user session in React?

I have a doubt about how to manage a user session in React, for example, in MVC.NET, you just do it only using the Session object (for example, Session["test"] = ""; ), but obviously React can't do that.

I read about using the state of a component, I believe it sets the state in the main component and passes this state to other components using props. I also saw people recommending using localStorage browser or cookies, but I do not know if this is a good idea or practice.

Is there a better way to manage session variables in React than localStorage or cookies?

+24
source share
3 answers

I would not use the state of the component, as this can be difficult to manage and can lead to problems that are difficult to fix.

You must use cookies or localStorage to store user session data. You can also use closure as a wrapper for your cookie or localStorage .

Here is a simple example of a UserProfile closure that will contain the username.

 var UserProfile = (function() { var full_name = ""; var getName = function() { return full_name; // Or pull this from cookie/localStorage }; var setName = function(name) { full_name = name; // Also set this in cookie/localStorage }; return { getName: getName, setName: setName } })(); export default UserProfile; 

When a user logs in, you can populate this object with a username, email address, etc.

 import UserProfile from './UserProfile'; UserProfile.setName("Some Guy"); 

Then you can get this data from any component in the application, when necessary.

 import UserProfile from './UserProfile'; UserProfile.getName(); 

Using a closure allows you to save data outside the global namespace and make it easily accessible from anywhere in your application.

+17
source

This is not the best way to manage a session in response. You can use web tokens to encrypt the data you want to save, you can use a different number of available services, the most popular of which are JSON web tokens (JWT) with web tokens, after which you can log out. some time if there was no action from the client. After creating the token, you can save it in local storage for easy access.

 jwt.sign({user}, 'secretkey', { expiresIn: '30s' }, (err, token) => { res.json({ token }); 

the user object here is the user data that you want to save in the session

 localStorage.setItem('session',JSON.stringify(token)); 
+1
source

To name a few, we can use redux-responsive to a session that has a good session management API, such as initSessionService , refreshFromLocalStorage , checkAuth and many others. It also provides some advanced functionality, such as Immutable JS .

As an alternative, we can use a reaction-web session that provides options such as callback and timeout .

0
source

Source: https://habr.com/ru/post/1264635/


All Articles