The web storage API provides mechanisms for the client’s browser to securely store and easily access key-value pairs. This is useful for storing simple data such as usernames or emails, as well as checking whether a user can access a particular resource by storing data such as access and refresh tokens.

We can easily view stored data on the client’s browser using JavaScript client-side code running in that browser, so if a user leaves the site and later returns, your JS code can read from window.localStorage to retrieve any data saved in it.
In this article, we’ll look at how to stringify and parse JavaScript objects into JSON strings so that they can be saved in localStorage. We’ll also learn the differences between localStorage, sessionStorage, and cookies, as well as the benefits and drawbacks of using cookies instead of localStorage.
localStorage?LocalStorage is a web storage mechanism that allows us to store data on the client’s browser that persists even after the browser window is closed. Data stored here can be accessed throughout a particular domain. For instance, data stored in the localStorage object from www.example.com can be accessed by any page on this domain.
And, according to w3schools, “the localStorage object stores the data with no expiration date. The data will not be deleted when the browser is closed and will be available the next day, week, or year.”
sessionStorage vs. localStorage vs. cookiessessionStorage is a web storage API that is used on the client-side to store data for a specific domain. It’s similar to window.localStorage, but it has an expiry time.
window.sessionStorage is active as long as the tab or browser is open and persists through page reloads and restores. When a document is loaded into a browser tab, a new page session is created and assigned to that tab. That page session is only valid for the tab in question.
Note: data stored in
sessionStorageis distinct to that page’s protocol. This means that data stored on a site accessed via HTTP is stored on a differentsessionStorageobject than data stored on the same site accessed via HTTPS.
localStorage works similarly to sessionStorage, but the difference is that data stored in localStorage is persistent and lasts forever for that specific domain unless the browser’s cache is cleared or we clear localStorage using JavaScript because localStorage data can only be manipulated by JavaScript.
Note: when the last private tab is closed, data stored in the
localStorageobject of a site opened in a private tab or incognito mode is cleared.
HTTP cookies, on the other hand, are text files that a website’s server creates and sends to new users who visit the site. When you connect, the server generates the information that is saved in a cookie. This information is labeled with an ID that is unique to you and your computer.
Cookies contain information that is specific to a particular user and is used to identify that user. They save data such as authentication information, shopping cart information, and so on to help personalize a user’s experience. They can, however, be a privacy nightmare, as we’ll see in the following section.
In this section, we’ll look at some of the pros and cons of working with cookies over localStorage.
localStorage or sessionStorage, which are only accessed by the application as client-side data storagelocalStorage, web applications can store an entire user-authored document on the client-side for performance reasons, but cookies do not handle this well, as they’re transmitted with every request made to the serverlocalStorage capacity of 10MBlocalStorageWhen working with the window.localStorage object, you should be familiar with the following methods: setItem, getItem, removeItem, clear, and key.
Let’s look at how to store JavaScript objects in the localStorage object using the setItem and getItem methods, as well as two JSON methods, stringify and parse.
setItem() – the setItem method is used to add data to a web storage object. It takes in two arguments, a key and value pair, window.localStorage.setItem("key", value)getItem() – the getItem method returns the value of the key name that’s passed to it, such as window.localStorage.getItem("key name") JSON.stringify – the JSON.stringify method converts any object or acceptable value into a string JSONJSON.parse – the JSON.parse method converts a string into its corresponding object or value as described by the stringLet’s see an example of how to store a JavaScript object in localStorage using the methods mentioned above:
//javascript
const myObject = {
name : "john doe",
age : 32,
gender : "male",
profession : "optician"
}
window.localStorage.setItem("myObject", JSON.stringify(myObject));
In the code block, we used the JSON.stringify() method to convert our JavaScript object into a string first because we can only store strings in the window.localStorage object.
If we try to store a JavaScript object without first converting it to a string, we will get an [object, object] response, as shown in the image.

[object object] is a string representation of an object instance, but its value is never read.
Now we need to retrieve our JavaScript object, which we previously saved as a JSON string. To do this, we need to parse the string.
//javascript
let newObject = window.localStorage.getItem("myObject");
console.log(JSON.parse(newObject));
Here, we retrieved our previously set JavaScript object by using the getItem method on the window.localStorage object and saving it into a variable. Next, we parsed that string into a JavaScript object and then logged it to the console.
If we try to retrieve the object without first parsing it, we would get back a string as a response. Here’s what I mean:

Some data types are not JSON-safe, and if such values are found during conversion, they are either excluded in an object or changed to null in an array.
Primitive data types like numbers, booleans, and strings are JSON-safe, while values like functions, undefined, symbols, date-objects are not JSON-safe.
In this article, we learned about a neat trick for storing JavaScript objects as JSON strings in the window.localStorage object. We can store more user information in a single key this way.
In summary, we can store JavaScript objects in localStorage by first converting them to strings with the JSON.stringify method, then back to objects with the JSON.parse method.
Debugging code is always a tedious task. But the more you understand your errors, the easier it is to fix them.
LogRocket allows you to understand these errors in new and unique ways. Our frontend monitoring solution tracks user engagement with your JavaScript frontends to give you the ability to see exactly what the user did that led to an error.
LogRocket records console logs, page load times, stack traces, slow network requests/responses with headers + bodies, browser metadata, and custom logs. Understanding the impact of your JavaScript code will never be easier!
D3.js is a powerful JavaScript library for creating tailored data visualizations. Let’s see why you should use D3.js in your next project.
Demonstrate how to automate releases and release notes with semantic-release in GitLab.
Learn all about how to implement push notifications in React Native in this ultimate guide and step-by-step tutorial.
The Effect library helps you better handle async code, types in async scenarios, and errors in TypeScript projects. Let’s see how.
One Reply to "Storing and retrieving JavaScript objects in localStorage"
It might be worth noting that there is a limit (~5mb) to how much you can store in localstorage. There are strategies ​to minify the data and still store it as JSON