Home > Web Front-end > JS Tutorial > Storing and retrieving JavaScript objects in localStorage

Storing and retrieving JavaScript objects in localStorage

DDD
Release: 2024-10-09 06:21:29
Original
584 people have browsed it

Written by Nelson Michael✏️

Editor’s note: This article was last updated by Rahul Chhodde on 7 August 2024 to offer a deeper exploration of storing objects in localStorage, such as techniques to serialize JavaScript objects using JSON.stringify, and situations where working with and storing multiple objects in localStorage is necessary.

The Web Storage API provides JavaScript-based mechanisms to securely store and access data as key-value pairs in the client's browser. This is useful for storing non-sensitive data such as user preferences, application states, and even API responses in some cases.

The two mechanisms of the Web Storage API, localStorage and sessionStorage, allow developers to store data persistently and temporarily. This stored data can be easily retrieved later and utilized to facilitate the user.

In this article, we'll learn how to stringify and parse JavaScript objects into JSON strings to save them in localStorage, and then reverse the process to retrieve the data. We'll also briefly cover the key differences between localStorage, sessionStorage, and HTTP cookies, highlighting the benefits and drawbacks of using localStorage over the other two.

What is localStorage?

The localStorage object is one of the two mechanisms of Web Storage that allow developers to store data on the client’s browser that persists even after the browser window is closed. This stored data can be accessed throughout a particular domain using easy-to-use API methods, some of which are shown below:

localStorage.setItem("myDataKey", "My data");
localStorage.getItem("myDataKey"); // "My data"
localStorage.removeItem("myDataKey");
Copy after login

Note that the data stored in the localStorage object from a domain can only be accessed or modified by pages of the same origin, which — in this case — stands for protocol, domain, and port collectively. You can verify this behavior using these methods in your browser’s developer console.

According to W3Schools, the localStorage object stores the data with no expiration date. The data will not be deleted even when the user leaves the page or closes the browser window; it will be available for future sessions. This ability to hold the data is known as data persistence in software and web development.

Using sessionStorage vs. localStorage

The second Web Storage mechanism, sessionStorage, is nearly identical to localStorage but differs in two ways: it temporarily stores data for the specified (or current) tab and does so for only a limited period.

The sessionStorage object stays active as long as the corresponding tab is open and persists data through page reloads and restorations. When a webpage is loaded into a browser tab, sessionStorage, if used, creates a new page session and assigns it to that tab. That page session is only valid for that particular origin accessed in that specific tab.

Note: Data stored in each kind of Web Storage is distinct for each protocol of a given page. 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.

Key differences between sessionStorage and localStorage

localStorage and sessionStorage work similarly, but the main difference is that data stored in localStorage is persistent, shared between tabs of the same origin, and lasts forever for that specific origin unless the browser's storage is cleared or we clear localStorage using JavaScript or manually.

Using Chrome DevTools, you can view the data in both localStorage and sessionStorage objects and observe the distinctions we just covered. Here’s a screenshot depicting locating both objects in the Application tab of DevTools: Storing and retrieving JavaScript objects in localStorage

To store and reuse information like user preferences, application states, API response, and larger chunks of data to facilitate perceived performance, we choose localStorage over sessionStorage, because this info should persist to be used occasionally to personalize and update the user experience.

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, which makes sense because it’s a private browsing session.

Web Storage vs. HTTP cookies

HTTP cookies are a conventional mechanism for storing small bits of data exchanged between the client and the server during each HTTP request.

Once connected to a client, the server generates certain bits of information, saves them in a cookie file, and sends them to the client’s browser. This information is labeled with a unique ID for each user and their computer, which helps the server identify the user whenever a connection is established.

Cookies carry information such as auth and session data, CSRF tokens, tracking data, and tiny, site-specific user preferences to help personalize a user's experience. However, they can be a privacy nightmare. We'll discuss this in the following segment.

Why and when to use cookies?

Cookies are not the recommended solution for storing larger volumes of data on the client side. They are better suited for session management and are one of the most widely supported solutions for doing so.

With each request, cookies 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 and open to vulnerabilities.

For session security, cookies marked as Secure and HttpOnly can minimize the chances of session hijacking, limiting XSS (cross-site scripting) and CSRF (cross-side request forgery) attacks on the user's browser during the session.

When not to use cookies

HTTP cookies have been a long-standing standard, and keeping your apps 100% cookie-free isn’t always possible. However, there are a few cases where you might want to avoid them:

  • Cookies are supposed to be transmitted with every request made to the server, which is why they are kept tiny and can’t hold data more than 4KB. This makes them unfit for caching big values like huge user preference data, application states, user-authored documents, etc.
  • Third-party cookies raise a serious privacy concern, as the site you’ve visited doesn’t create or own them. Such cookies are usually linked to tracking user data, which puts them under suspicion, and many browsers are preparing to restrict them to safeguard user privacy

These points leave us to store our heaps of non-sensitive data in localStorage. Such situations often demand saving complex data like JavaScript objects locally, which requires a slightly different approach.

How to store a JavaScript object in localStorage

Modern web apps often demand saving JavaScript objects locally to provide offline access, restore application state, or cache an API response for perceived performance benefits.

Note that such data shouldn’t carry sensitive information, as once stored in Web Storage, it becomes accessible to any JavaScript code running on the same origin.

Let's start by gaining a basic understanding of how to work with localStorage by exploring its methods and properties for various use cases:

  • setItem(): Adds data to a Web Storage object using its two arguments, a key, and a value: localStorage.setItem("key", "value")
  • getItem(): Returns the value of the key name that’s passed to it: localStorage.getItem("key")
  • **removeItem()**: Removes a key that’s passed to it with its corresponding value: localStorage.removeItem("key")
  • clear(): Clears all the key-value pairs in the associated storage and should be used with caution: localStorage.clear()
  • **key()**: Returns the key at the specified index in the storage: localStorage.key(0)
  • length: Returns the total number of key-value pairs stored in the associated storage: localStorage.length

You can learn more about these methods on MDN’s Web Storage API docs.

The example below demonstrates data persistence accomplished using some of these Web Storage API methods. Click the Current count button, rerun the CodePen, and see the count data persisting using localStorage:

See the Pen localStorage in action by Rahul (@_rahul) on CodePen.

In the demo above, whenever you click the count or the clear button, multiple localStorage items are created, read, or modified and the changes to the corresponding values are reflected in the frontend.

JavaScript object serialization

Storing JavaScript object data in Web Storage is a bit tricky, as it allows you to store only string values. 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 below:
Storing and retrieving JavaScript objects in localStorage [object Object] is a string representation of an object instance whose value was never read at the time of storing the data, which will result in data loss.

The correct way to store object data to localStorage is to first convert it to a string. Then, we can move on to the storage procedure.

This object-to-string conversion of object data is known as serialization, and turning this converted string back to object data is called deserialization. Let’s briefly discuss two important JSON methods that are responsible for object data serialization and deserialization:

  • JSON.stringify: Converts any object value into a string JSON (serialization)
  • JSON.parse: Turns a JSON string into its corresponding object or value (deserialization)

Now, utilizing the setItem method with JSON stringify, we can easily convert a JavaScript object to a JSON string and push it to the localStorage object. Here’s a quick example to demonstrate this:

const userObj = {
  name: "John Doe",
  age: 32,
  gender: "Male",
  profession: "Optician" 
};

localStorage.setItem("userObj", JSON.stringify(myObject));
Copy after login

Now, if we try to retrieve the object data without deserializing it, we will receive a JSON string instead of an object, which makes sense, as it is what we stored to localStorage.

We need to deserialize this JSON string data using the JSON parse method to turn it back into a JavaScript object:

let newObject = localStorage.getItem("myObject");
console.log(JSON.parse(newObject));
Copy after login

Here, we retrieved our previously set JavaScript object using the getItem method on the localStorage object and saved it into a variable. Next, we parsed that string into a JavaScript object and finally logged it to the console:
Storing and retrieving JavaScript objects in localStorage

More examples of storing objects in localStorage

  • Storing Date objects: Constructing an object using the current timestamp using the Date object and a random value, and saving it to or clearing it from the localStorage using button inputs
  • Persisting remote data: Fetching remote data from a dummy API and storing it in localStorage; the network fetch in this example is only triggered when no associated data in localStorage is found

Storing multiple objects in localStorage

Let’s say we have a bunch of similar objects, and we want to group all of them and store them as one JSON string in the localStorage. We can turn them into an object array and then serialize them as shown below:

const todos = [todo1, todo2, todo3];
localStorage.setItem("todos", JSON.stringify(todos));
Copy after login

If you have bigger chunks of data to work with, you might want to store each of them with separate keys, but accessing all of them quickly can be done using this namespace approach:

// Storing
localStorage.setItem('todos:1', JSON.stringify(todo1));
localStorage.setItem('todos:2', JSON.stringify(todo2));

// Retrieving
const keys = Object.keys(localStorage).filter(key => key.startsWith('todos:'));
const todos = keys.map(key => JSON.parse(localStorage.getItem(key)));
Copy after login

Limitations of storing objects to localStorage

localStorage is one of the mechanisms of the Web Storage API. The API provides 5-10MB of storage per origin, and the exact storage may vary depending on the browser. Respecting this size limit, you should avoid storing more than 3-4MB of data per origin in Web Storage objects.

Keep in mind that Web Storage API operations are synchronous and block the main thread, therefore performing heavy operations using it may block other resources from loading in the browser.

Types of data that can be stored as a JSON string

Primitive data types like numbers, Booleans, and strings are JSON-safe, while values like functions, undefined, symbols, and Date objects are not JSON-safe. If no JSON-safe values are found during conversion, they are either excluded from an object or changed to null in an array.

Note: Some of these such values can be made JSON-safe, for example, we used the toISOstring method with the Date object in this example to make it JSON-safe before pushing it to Web Storage.

Conclusion

In this article, we learned a useful technique for storing multiple bits of information in a single localStorage key and using the JSON stringify and parse methods. We also covered some working demonstrations that apply this approach to different tasks, as well as storing and retrieving multiple JavaScript objects from localStorage.

In summary, we should be mindful of the data we store locally, and take advantage of the localStorage object to store JavaScript objects by first converting them to JSON strings with the JSON.stringify method and then turning them back to objects with the JSON.parse method.


LogRocket: 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 see exactly what the user did that led to an error.

Storing and retrieving JavaScript objects in localStorage

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!

Try it for free.

The above is the detailed content of Storing and retrieving JavaScript objects in localStorage. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template