'What is the best way to manage a user's session in React?
I have a doubt about how to manage a user's session in React, for example in MVC .NET you only just do this using the Session object (e.g. Session["test"] = "";
), but obviously React can not do this.
I was reading about using the component state, I suppose that sets the state at the principal component and passes this state to other components using props. Also I saw people recommending the use the browser's localStorage
or cookies, but I don't know if this if a good idea or practice.
Is there a better way to manage sessions variables in React than localStorage
or cookies?
Solution 1:[1]
I would avoid using component state since this could be difficult to manage and prone to issues that can be difficult to troubleshoot.
You should use either cookies
or localStorage
for persisting a user's session data. You can also use a closure as a wrapper around your cookie
or localStorage
data.
Here is a simple example of a UserProfile
closure that will hold the user's name.
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 user name, email address etc.
import UserProfile from './UserProfile';
UserProfile.setName("Some Guy");
Then you can get this data from any component in your app when needed.
import UserProfile from './UserProfile';
UserProfile.getName();
Using a closure will keep data outside of the global namespace, and make it is easily accessible from anywhere in your app.
Solution 2:[2]
There is a React module called react-client-session
that makes storing client side session data very easy. The git repo is here.
This is implemented in a similar way as the closure approach in my other answer, however it also supports persistence using 3 different persistence stores. The default store is memory(not persistent).
- Cookie
- localStorage
- sessionStorage
After installing, just set the desired store type where you mount the root component ...
import { ReactSession } from 'react-client-session';
ReactSession.setStoreType("localStorage");
... and set/get key value pairs from anywhere in your app:
import { ReactSession } from 'react-client-session';
ReactSession.set("username", "Bob");
ReactSession.get("username"); // Returns "Bob"
Solution 3:[3]
This not the best way to manage session in react you can use web tokens to encrypt your data that you want save,you can use various number of services available a popular one is JSON web tokens(JWT) with web-tokens you can logout after some time if there no action from the client And after creating the token you can store it in your local storage for ease of access.
jwt.sign({user}, 'secretkey', { expiresIn: '30s' }, (err, token) => {
res.json({
token
});
user object in here is the user data which you want to keep in the session
localStorage.setItem('session',JSON.stringify(token));
Solution 4:[4]
To name a few we can use redux-react-session which is having good API for session management like, initSessionService
, refreshFromLocalStorage
, checkAuth
and many other. It also provide some advanced functionality like Immutable JS
.
Alternatively we can leverage react-web-session which provides options like callback
and timeout
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Kenton Blacutt |
Solution 3 | kirito |
Solution 4 | Chirag Visavadiya |