Session Management

You should use either cookies or localStorage for persisting a user’s session data. Another option is to use a closure as a wrapper around your cookie or localStorage.

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.

JWT

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));

Share this post
[social_warfare]
Redux
Babel Compiler

Get industry recognized certification – Contact us

keyboard_arrow_up