[session] 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?

This question is related to session reactjs

The answer is


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

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

  1. Cookie
  2. localStorage
  3. 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"

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.


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.


Examples related to session

What is the best way to manage a user's session in React? Spring Boot Java Config Set Session Timeout PHP Unset Session Variable How to kill all active and inactive oracle sessions for user Difference between request.getSession() and request.getSession(true) PHP - Session destroy after closing browser Get Current Session Value in JavaScript? Invalidating JSON Web Tokens How to fix org.hibernate.LazyInitializationException - could not initialize proxy - no Session How can I get session id in php and show it?

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release