88

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?

Taylor Wood
  • 15,886
  • 1
  • 20
  • 37
ernesto petit
  • 1,436
  • 1
  • 14
  • 19
  • 3
    Session is executed on server side. React is working on client side so the only option is by using local storage to store temporary information. – Sulung Nugroho Apr 25 '19 at 02:27

4 Answers4

49

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.

grizzthedj
  • 7,131
  • 16
  • 42
  • 62
  • 6
    Is it a safe procedure? – urb Mar 12 '18 at 12:42
  • 2
    It is safe if you are storing user data that is already visible on the web site(e.g. name, email, phone number etc.). I would not use this to store a credit card number for example. ;) – grizzthedj Mar 12 '18 at 12:49
  • Just to get my understanding right, this method is not a full implementation for a session, right? It still needs to be persisted somehow. – Nathan May 06 '18 at 20:47
  • Correct. The UserProfile closure could be modified to store the attributes in localStorage as well, if persistence is required – grizzthedj May 06 '18 at 20:59
  • @ernesto petit: Does this help? This question is getting visibility, so you should accept this answer, if it answers your question. – grizzthedj May 11 '18 at 00:47
  • 2
    Is not the same thing to define some class instead use Clojure syntax? What is the advantage? – Enrique René May 20 '19 at 12:00
  • Looks like this code ended up here: https://medium.com/@atif.ali.ati/user-session-in-react-js-aa749bc4faf6 – matt burns Apr 20 '21 at 20:44
  • 6
    @mattburns can they just take an answer like that without giving credit? Looks like plagiarism to me. – S.Alvi Aug 31 '21 at 04:04
  • @grizzthedj Would you want the closure accessible via Context or Redux or are you suggesting something else? – Jay J Feb 28 '22 at 17:32
22

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"
Kenton Blacutt
  • 160
  • 2
  • 8
grizzthedj
  • 7,131
  • 16
  • 42
  • 62
9

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));
kirito
  • 221
  • 2
  • 8
  • 6
    Storing tokens in localStorage is unsafe; localStorage isn't a secure store and if a bad actor grabs that token they can act on your behalf. – Far_Eggs Aug 27 '18 at 12:58
  • @Far_Eggs Why is it unsafe? So where should one save tokens? or what approach do you recommend? – Paulo Madroñero Oct 03 '18 at 19:12
  • 37
    Please stop recommending JWT for sessions. They're not meant for that. Read this for further info: http://cryto.net/~joepie91/blog/2016/06/13/stop-using-jwt-for-sessions/ – justarandomguy Nov 11 '18 at 13:47
  • 3
    @PauloMadroñero In this case cookies are a better option when used correctly. With cookies you can, for example, a) prevent JS code to read/write the session cookie (think a 3rd party .js acting bad), b) limit usage to a specific domain to prevent hijacking (SecureSite), c) limit usage to https only to prevent bad actors from sniffing, others. – cmlndz Jan 14 '20 at 14:12
5

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.