Nelson Michael Nelson Michael is a frontend developer from Nigeria. When he's not meddling with CSS, he spends his time writing, sharing what he knows, and playing games.

Storing and retrieving JavaScript objects in localStorage

4 min read 1267

JavaScript Logo Over a Stack of Cookies

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.

What is 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.”

Using sessionStorage vs. localStorage vs. cookies

sessionStorage 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 sessionStorage is distinct to that page’s protocol. This means that data stored on a site accessed via HTTP is stored on a different sessionStorage object 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 localStorage object 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.

Using cookies for web storage

In this section, we’ll look at some of the pros and cons of working with cookies over localStorage.

Why use cookies?

  • Cookies are better suited for performing authentication-related tasks. They are sent to the server in the HTTP headers from the browser, as opposed to using localStorage or sessionStorage, which are only accessed by the application as client-side data storage
  • Cookies can be marked as HTTP only, limiting XSS (cross-site scripting) attacks to the user’s browser during the session, but this does not guarantee full immunity to XSS attacks

The cons of using cookies

  • Cookies are prone to cyber attacks, and hijacked cookies can enable access to a user’s browsing sessions.
  • Third-party cookies are a privacy nightmare. They are created by a site that’s different from the current site you’re viewing. They are usually linked to ads on a webpage, so visiting a site with seven ads may generate seven cookies, even if a user doesn’t click on an ad
  • With localStorage, 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 server
  • Storage capacity for cookies is only about 4KBm in contrast to localStorage capacity of 10MB
  • Because cookies are stored as text files on the hard drive, they pose serious security risks. Any intruder can easily open these files and view the information contained within

How to store the JavaScript object in localStorage

When 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 JSON
  • JSON.parse – the JSON.parse method converts a string into its corresponding object or value as described by the string

Let’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 Response

[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:

String Response

Types of data that can be stored as a JSON string

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.

Conclusion

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.

: Debug JavaScript errors more easily by understanding the context

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 find out exactly what the user did that led to an error.

LogRocket records console logs, page load times, stacktraces, slow network requests/responses with headers + bodies, browser metadata, and custom logs. Understanding the impact of your JavaScript code will never be easier!

.
Nelson Michael Nelson Michael is a frontend developer from Nigeria. When he's not meddling with CSS, he spends his time writing, sharing what he knows, and playing games.

One Reply to “Storing and retrieving JavaScript objects in localStorage”

  1. 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

Leave a Reply