localStorage for Session Management
What is localStorage?
localStorage in React is a way to store data in the browser's localStorage. Data is stored against the domain, so it can be accessed from different pages of the same domain. This is useful for storing data that is not sensitive, such as user login details, or session data. One can see the data in the browser's localStorage by opening the developer tools. Data is stored against a key and can be retrieved using the same key.
How to use localStorage?
In React, localStorage is accessed using the localStorage object. The localStorage object is a global object, so it can be accessed from anywhere in the application. The localStorage object has the following methods:
localStorage.setItem()- to set an item in thelocalStoragelocalStorage.getItem()- to get an item from thelocalStoragelocalStorage.removeItem()- to remove an item from thelocalStoragelocalStorage.clear()- to clear all the items from thelocalStoragelocalStorage.key()- to get the key of an item at a specific indexlocalStorage.length- to get the number of items in thelocalStoragelocalStorage.onstorage- to set a callback function that will be called when thelocalStorageis changed
localStorage.setItem()
setItem takes two parameters: the key and the value. The value can be any type of data but must be serializable. The key is a string, it should be unique, and it is used to retrieve the data later. The setItem method returns undefined.
localStorage.setItem("key", "value");
Serialization is the process of converting a data structure into a string representation. The string representation of the data is stored in the localStorage. For example, if you want to store an array of numbers or a complex object, you can't just store the array or object in the localStorage. You must convert it to a string representation, and then store it in the localStorage. In this case, you can use the JSON.stringify method to convert the array/object to a string.
Array:
localStorage.setItem("key", JSON.stringify([1, 2, 3]));
Object:
localStorage.setItem("key", JSON.stringify({ name: "John", age: 30 }));
And to retrieve the data, you can use the JSON.parse method to convert the string back to an array/object. I will show an example of how to use the JSON.parse method in the next section.
localStorage.getItem()
The getItem method takes a single parameter, the key. The getItem method returns the value stored against the key. If no value is stored against the key, it returns undefined.
localStorage.getItem("key");
If they stored an array or object in the localStorage by using the JSON.stringify method, now you have to use the JSON.parse method to convert the string back to an array/object.
JSON.parse(localStorage.getItem("key"));
localStorage.removeItem()
The removeItem method takes a single parameter, the key. The removeItem method returns undefined. It removes the value stored against the key.
localStorage.removeItem("key");
localStorage.clear()
The clear method removes ALL THE VALUES stored in the localStorage. It returns undefined. Normally, this method is not used as it is not recommended to clear the localStorage. Cause it removes all the data stored in the localStorage.
localStorage.clear();
localStorage.key()
The key method returns the key of the item that is currently being accessed. It returns undefined if no item is being accessed.
localStorage.key();
localStorage.length
The length property returns the number of items stored in the localStorage.
localStorage.length;
localStorage.onstorage
The onstorage property is used to set a callback function that will be called when the localStorage is changed. The callback function takes a single parameter, the event object. The event object has the following properties:
key- the key of the item that was changedoldValue- the old value of the item that was changednewValue- the new value of the item that was changedurl- the url of the page that changed thelocalStorage
localStorage.onstorage = (event) => {
console.log(event);
};
localStorage for Session Management
In this section, I will show how to use localStorage to store session data. First of all, what is the session? and why is it important?
What is Session?
A session is created when a user logs in to the application. The session is destroyed when the user logs out of the application. For example, you logged in to a website. It will store the user's login details like username, user_id, jwt token, etc. Whenever you again want to use the website, first of all website will check if the user is logged in. If the user is logged in, it will check if the session is still valid. If the session is valid, it will display the user's profile. If the session is not valid, it will redirect the user to the login page.
Why is it important?
A session is important because it stores the user's login details. It is used to check if the user is logged in. If the user is not logged in, it will redirect the user to the login page. As I mentioned earlier, the session is created when the user logs in to the application. The session is destroyed when the user logs out of the application. This is a way to store the user's login details.
For example, you logged in to a website. It will store your details like username, user_id, jwt token, etc. And now when that website hits the server, the front end will send the jwt token to the server. The server will recognize the jwt token and will return data that is related to the user, not all the data that is stored in the database.
How to use localStorage for session management?
While login to the application, we will store the user's login details in the localStorage. And while logging out of the application, you will remove the user's login details from the localStorage. Normally I store the user's token in the localStorage that is returned by the server. And while logging out, I remove the token from the localStorage.
On Login, I will store the user's login details in the localStorage.
localStorage.setItem(
"login-user",
JSON.stringify({ username: "john", user_id: 1, token: "<token>" }),
);
On Logging out, I will remove the user's login details from the localStorage.
localStorage.removeItem("login-user");
Where I need the user's token, I will get it from the localStorage like this:
const user = JSON.parse(localStorage.getItem("login-user"));
localStorage vs sessionStorage
The localStorage and sessionStorage are similar. The only difference is that the localStorage stores the data until the user clears the localStorage. And the sessionStorage stores the data until the user closes the browser.
localStorage vs cookie
The localStorage and cookie are similar. The only difference is that the client itself stores data in localStorage in the browser, whereas the server stores cookie in the browser from the server.
localStorage in Node.js
As I mentioned earlier, localStorage is used to store data in the browser. But what if you want to use the localStorage in Node.js? Is it possible?
Node.js doesn't have the localStorage object. But, if you want to use the localStorage object in Node.js, there are some packages available. One of them is node-localstorage. With the help of node-localstorage, you can use the localStorage object in Node.js.
You can install the package by running the following command:
- npm
- Yarn
- pnpm
- Bun
npm install node-localstorage
yarn add node-localstorage
pnpm add node-localstorage
bun add node-localstorage
You can use the node-localstorage package like this:
const LocalStorage = require("node-localstorage").LocalStorage;
// const localStorage = new LocalStorage("./scratch");
localStorage.setItem("key", "value");
localStorage.getItem("key");
localStorage.removeItem("key");
:::
Example
In this example, I will show how to use the localStorage object in React.js. I will create a simple application that will store the user's login details in the localStorage. When the user refreshes the page, the user's login details will be displayed on the page. And when the user clicks on the logout button, the user's login details will be removed from the localStorage.
I will use the same code that I used in the previous example, but there pages do not have any functionality. I will add the functionality in this example.
We have three pages in this example:
Register
The register page will have a form that will have three fields:
- Name
- Password
When the user clicks on the register button, the user's details will be stored in the localStorage. The user will be redirected to the login page.
import React, { useState } from "react";
import { useHistory } from "react-router-dom";
const Register = () => {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const history = useHistory();
React.useEffect(() => {
// If the user is already logged in, redirect to the home page
if (localStorage.getItem("login-user")) {
history.push("/");
}
}, []);
const handleSubmit = (e) => {
e.preventDefault();
const users = JSON.parse(localStorage.getItem("users"));
const userAlreadyExists = users.find((user) => user.email === email);
if (userAlreadyExists) {
alert("User already exists");
return;
}
users.push({ name, email, password });
localStorage.setItem("users", JSON.stringify(users));
history.push("/login");
};
return (
<div className="container">
<div className="row">
<div className="col-md-6 offset-md-3">
<div className="card">
<div className="card-header">Register</div>
<div className="card-body">
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="name">Name</label>
<input
type="text"
className="form-control"
id="name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
<div className="form-group">
<label htmlFor="email">Email</label>
<input
type="email"
className="form-control"
id="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input
type="password"
className="form-control"
id="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<button type="submit" className="btn btn-primary">
Register
</button>
</form>
</div>
</div>
</div>
</div>
</div>
);
};
Login
The login page will have a form that will have two fields:
- Password
When the user clicks on the login button, the user's details will be stored in the localStorage. The user will be redirected to the home page.
import React, { useState } from "react";
const Login = () => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
React.useEffect(() => {
// If the user is already logged in, redirect to the home page
if (localStorage.getItem("login-user")) {
history.push("/");
}
}, []);
const handleSubmit = (e) => {
e.preventDefault();
const users = JSON.parse(localStorage.getItem("users"));
const user = users.find(
(user) => user.email === email && user.password === password,
);
if (!user) {
alert("Invalid email or password");
return;
}
localStorage.setItem("login-user", JSON.stringify({ email, password }));
history.push("/");
};
return (
<div className="container">
<div className="row">
<div className="col-md-6 offset-md-3">
<div className="card">
<div className="card-header">Login</div>
<div className="card-body">
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="email">Email</label>
<input
type="email"
className="form-control"
id="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input
type="password"
className="form-control"
id="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<button type="submit" className="btn btn-primary">
Login
</button>
</form>
</div>
</div>
</div>
</div>
</div>
);
};
Home
The home page will have a logout button. When the user clicks on the logout button, the user's details will be removed from the localStorage. The user will be redirected to the login page.
import React from "react";
const Home = () => {
const handleLogout = () => {
localStorage.removeItem("login-user");
history.push("/login");
};
return (
<div className="container">
<div className="row">
<div className="col-md-6 offset-md-3">
<div className="card">
<div className="card-header">Home</div>
<div className="card-body">
<button className="btn btn-primary" onClick={handleLogout}>
Logout
</button>
</div>
</div>
</div>
</div>
</div>
);
};
App
The App component will have the routes for the register, login, and home pages.
import React from "react";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import Register from "./pages/register";
import Login from "./pages/login";
import Home from "./pages/home";
const App = () => {
return (
<Router>
<Switch>
<Route path="/register">
<Register />
</Route>
<Route path="/login">
<Login />
</Route>
<Route path="/">
<Home />
</Route>
</Switch>
</Router>
);
};
Code
You can get the complete code from here