Introduction
As a web developer, you've likely encountered the need to persist data across different sessions or even tabs in a browser. This is where HTML5's localStorage and sessionStorage come in handy. These two web storage objects allow you to store data right in the user's browser, no server-side code required.
In this article, we'll take a look at what these storage objects are, and how you can utilize them to store your JavaScript objects.
What is localStorage/sessionStorage?
localStorage and sessionStorage are part of the Web Storage API, which provides consistent ways for browsers to store key/value pairs. These pairs are kept in a web browser with no expiration date in the case of localStorage, and for the duration of the page session in case of sessionStorage.
Here's a simple way to think about it:
localStorage
is like a box in your garage where you store things you might need later. It's just always there. It persists across different sessions and even if you close and reopen your browser.sessionStorage
, on the other hand, is like a backpack you carry around. It only lasts as long as your "journey" (or in web terms, your session). If you close the tab or the browser, the data vanishes.
Here's a basic example of how to use them:
// Storing data
localStorage.setItem('key', 'value');
sessionStorage.setItem('key', 'value');
// Retrieving data
let localValue = localStorage.getItem('key');
let sessionValue = sessionStorage.getItem('key');
Note: Both localStorage and sessionStorage are limited to storing string data only. So, if you want to store objects, you'll need to convert them into strings using JSON.stringify()
. We'll cover this in later sections.
While these storage objects are incredibly useful, they shouldn't be used for sensitive data like passwords or credit card information, as the data is not encrypted and can be accessed by any script on your site.
How to Store Objects in localStorage
Now that we have a better understanding of what localStorage
is, let's look at how to actually do it. As mentioned earlier, localStorage
can only store strings. So, we'll need to convert our object to a string before storing it.
Here's an example of how you might do this:
let user = {
name: 'John Doe',
email: '[email protected]'
};
// Convert the user object into a string using JSON.stringify
let userString = JSON.stringify(user);
// Store the stringified user object in localStorage
localStorage.setItem('user', userString);
In this code, we first create a user
object with name
and email
properties. We then convert this object into a string using the JSON.stringify
method. This method takes an object and returns a string representation of that object.
Finally, we store the stringified object in localStorage
using the setItem
method. This method takes two arguments: the key to store the data under, and the data itself.
Now, if you open your browser's developer tools and navigate to the Application tab, you should see your stored data under the localStorage section.
Note: The JSON.stringify
method can also be used to convert arrays and other complex data types to a string format. This makes it a versatile tool for storing a wide range of data in localStorage
.
How to Store Objects in sessionStorage
Just like localStorage, sessionStorage also provides the ability to store key-value pairs. However, there is a key difference between the two: sessionStorage retains data for only as long as the session is active - that is, until the user closes the tab or browser. This can be useful for storing temporary data like form inputs, or other session-specific information.
Let's see how we can store objects in sessionStorage. Just like with localStorage, we cannot directly store objects as they are. We first need to convert them into a string using JSON.stringify()
. Here's an example:
let user = {
name: 'John Doe',
age: 25,
email: '[email protected]'
};
// Convert the user object into a string
let userString = JSON.stringify(user);
// Store the stringified object in sessionStorage
sessionStorage.setItem('user', userString);
In the above example, we first define an object user
with some properties. We then convert this object into a string using JSON.stringify()
, and store it in sessionStorage using sessionStorage.setItem()
.
Retrieving Stored Objects from localStorage/sessionStorage
Now that we've stored our objects in localStorage or sessionStorage, we'll likely want to retrieve them at some point. The process for this is fairly straightforward, but does require a couple of steps due to the fact that we've stored our objects as strings.
Here's how we can retrieve our user
object from sessionStorage:
// Get the stringified object from sessionStorage
let userString = sessionStorage.getItem('user');
// Parse the string back into an object
let user = JSON.parse(userString);
console.log(user);
When we run this code, we'll see our original user
object logged to the console:
{
name: 'John Doe',
age: 25,
email: '[email protected]'
}
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
The process for retrieving objects from localStorage is identical, just replace sessionStorage
with localStorage
.
Note: Make sure to always use JSON.parse()
when retrieving objects from localStorage or sessionStorage. If you forget to do this, you'll be working with a string representation of your object, rather than the object itself.
Conclusion
In this article, we've covered the basics of how to store, retrieve, and work with objects in HTML5's localStorage and sessionStorage. We've seen how these web storage mechanisms can provide a simple and effective way to persist data across browser sessions, all while maintaining a high level of performance and security.
One common use case for localStorage and sessionStorage is storing user preferences. For example, if a user prefers a dark theme for your website, you could store this preference in localStorage and apply it every time the user visits.
Here's a quick recap of what we covered:
- localStorage and sessionStorage are web storage mechanisms provided by HTML5.
- localStorage persists data across sessions, while sessionStorage only persists data for the duration of the current session.
- You can store objects in localStorage or sessionStorage by converting them to a string format using
JSON.stringify()
. - You can retrieve objects from localStorage or sessionStorage by parsing the stored string back into an object using
JSON.parse()
.