How to Store Login Sessions with LocalStorage and SessionStorage

Save Current LoggedIn user in SessionStorage and information of all the users from LocalStorage, all using plain JavaScript!

By Rasleen Kaur

October 24th, 2020

JavaScript is a lightweight scripting language, yet it provides such a great number of functionality, from making dynamic webpages to creating servers, mobile applications, etc. Two of the great functionalities Modern JavaScript can work with, are LocalStorage and SessionStorage.

The Demo

LocalStorage vs SessionStorage

Both can be accessed from Inspect Element > Application > LocalStorage or SessionStorage . Their names specify the difference between them, both store the information, but SessionStorage stores it for the current session while LocalStorage stores the information locally on your system.

When you change your current tab or browser window, the session expires, and hence, information is lost automatically, while LS doesn’t work that way!

So, for storing user information like user ID and password, we will use LocalStorage and the currently logged-in user’s info will be visible inside the SessionStorage itself! Pretty cool stuff👩🏻‍💻!

Time for the Implementation

The HTML form looks something like this, we will be extracting the username and password from this form and use it in our JS code.

...
<body>
  <div>
    <ul id="listuser">
      <h3> All users here: </h3>
    </ul> 
  </div>
  
<form onsubmit="return false">

<div class="container">

<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter Username" id= "uname"                  name="uname" required>

<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" id="psw" name="psw" required>

<button type="submit" onclick="Login()">Login</button>
    
</div>
</form>
</body>
...

The user ID and password are stored in LS as an array of objects. For this, we will create an array, and push the objects per user, to the array. The password must be stored in the LocalStorage in encrypted form, else they can be easily extracted out.

function btoa(‘string’) encodes the string passed while atob(‘encoded_string’) does the decoding of the encoded string.

function Login()
{
 var a = new Array();
 up1 = new Object();
 up2 = new Object();
 
up1={
 name:’[abcd@gmail.com](mailto:abcd@gmail.com)’,
 password:btoa(’abc@12')
};

up2={
 name:’[bcd@gmail.com](mailto:bcd@gmail.com)’,
 password:btoa(’bcd@12')
};

a.push(up1);
a.push(up2);

Extracting the currently logged-in user information

Simply, the username and password from the form submitted will be the current user details and we will store them in SessionStorage, using the setItem method, that takes in a (key, value) pair. Similarly, if you want to take out the values, use getItem(‘key’). Remember, here the key will be like — array[‘array_name’][userID]

var username = document.getElementById(‘uname’).value;
var password = document.getElementById(‘psw’).value;

sessionStorage.setItem(“currentloggedin”,username);

Storing the array of user objects. LocalStorage stores only string values, Json.stringify() does this for us!

localStorage.setItem('all_users',JSON.stringify(a));

Displaying the users on the webpage after logging-in

Time to parse through the array of objects we stored above and displaying a list of users appended to the

    as an
  • element dynamically. In the Login() function, add the following code:

    a=JSON.parse((localStorage.getItem("all_users")));
    
    a.push({name: username, password: password});
    
    localStorage.setItem('name',JSON.stringify(a));
    
    for(var i=0; i<a.length; i++)
      {
       var li = document.createElement("li");
       li.innerHTML=a[i]['name'];
       document.getElementById("listuser").appendChild(li);
      }
    

    Additional Case: Authentication of user

    I will be using the JavaScript map for checking the validity of the user information from the LocalStorage and declaring a successful Login, if the username and passwords record exists in the LocalStorage. For this, we need to convert the user information in the form of Array of Objects to Hash-map.

    Map( ) in JavaScript — The Optimization

    JS provides the functionality of Hash-map using the .map( ) function, in which objects can be stored as a [key , value] pair, and can be accessed as hashmap[key] = value;

    Here, I have stored the Email ID as the key, and password as the value. Remember to use atob(‘password’) to decode it for comparing the one stored in the LocalStorage.

    function Login()
    {
       const hash = Object.fromEntries(
       a.map(e => [e.name, e.password])
    )
    
    var username = document.getElementById('uname').value;
    var password = document.getElementById('psw').value;
    
    for (let key of hash) 
    {
        
        if(key[0] === username && key[1]===atob(password))
         {
             alert('Login successful');
         }
     
    else
         {
             alert('Login fail');
         }
    }
    

    Object.fromEntries() help us to retrieve all the objects, and each array of object is converted or mapped into a hashmap entry using the map( ) function. This is the more optimised and an efficient way of storing things inside LocalStorage.

    Iterating the Hashmap containing User Information

    Their are many complex ways to iterate through the maps, ranging from usage of reduce( ) function to using Object.assign( ).

    Using reduce( )

    var hashmap = a.reduce(function(map, obj) {
        map[obj.key] = obj.val;
        return map;
    }, {});
    

    2. Using Object.assign( )

    const hashmap = Object.assign({}, ...(<{}>a.map(s => ({[s.key]:s.value}))));
    

    The easiest way of iterating the hashmap is to run a for loop and it returns the (key,value) pair which can be accessed as key[0] and key[1] respectively.

    JavaScript is really fun and it always contains some features left undiscovered! Keep on exploring and create innovative stuff out of it!



Continue Learning