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.
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");
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.
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.
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:
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.
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.
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.
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:
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.
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:
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.
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:
[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:
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));
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));
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:
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));
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)));
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.
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.
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.
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!
Try it for free.
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3