How to Use HTML5 Local Storage and Session Storage

The article will show you how to save content on a user's browser using the HTML5 web storage capability.


What is Web Storage?

The HTML5 web storage feature provides a way to locally store information on the user's computer, similar to cookies but with improved speed and capacity. However, it is important to note that web storage does not offer enhanced security compared to cookies.

Web storage differs from cookies in several aspects. Firstly, the information stored in web storage is not sent to the web server with every request, unlike cookies. Additionally, while cookies have a limited data storage capacity of around 4KB, web storage allows for storing up to 5MB of data.

There are two types of web storage available:

  • Local storage — Using the localStorage object, enables the storage of data for the entire website on a permanent basis. This means that the stored local data will persist (for lifetime) even when the user closes the browser and will remain accessible on subsequent visits.
  • Session storage — Using the sessionStorage object, stores data temporarily for a single browser window or tab. The data in session storage is discarded when the session ends, such as when the user closes the browser window or tab.

Tip: It is worth noting that the HTML5 web storage feature is supported by major modern web browsers, including Firefox, Chrome, Opera, Safari, and Internet Explorer 8 and above.

HTML web storage, including local storage and session storage, provides a powerful means of storing data in web applications. With HTML5 web storage functionality, developers can customize the behavior of web storage to suit their specific needs. By organizing data effectively in HTML web storage, developers can optimize performance and leverage the performance advantages it offers over traditional cookies. It is important, however, to consider security considerations when using HTML web storage to ensure the protection of user data.


List of Methods and Properties of HTML5 Web Storage

Here's a list of the methods and properties available for both localStorage and sessionStorage:

  1. setItem(key, value): Stores a key-value pair in the storage. The key serves as the identifier for the data entry to be stored, while the value represents the content that can be stored, typically in the form of a string.
  2. getItem(key): Retrieves the value associated with the specified key. The key refers to the specific name that is used to retrieve the associated data.
  3. removeItem(key): Removes the key-value pair associated with the specified key. The key denotes the specific name linked to the removal of a data entry.
  4. Clear(): Removes all key-value pairs from the storage.
  5. key(index): Retrieves the name of the key at the specified index. The index indicates the numerical position required to retrieve the desired key.
  6. length: Returns the number of key-value pairs stored in the storage.

Here's a simple example demonstrating the usage of some of these methods and properties:

<script>
// Storing data in localStorage
localStorage.setItem('first_name', 'suresh');
localStorage.setItem('age', '33');

// Retrieving data from localStorage
var fname = localStorage.getItem('first_name');
var age = localStorage.getItem('age');

console.log('First Name:', fname); // Output: First Name: suresh
console.log('Age:', age);       // Output: Age: 33

// Checking the number of key-value pairs in localStorage
var itemCount = localStorage.length;
console.log('Total items:', itemCount); // Output: Total items: 2

// Removing a key from localStorage
localStorage.removeItem('age');

// Clearing all data from localStorage
localStorage.clear();

// Checking the number of key-value pairs in localStorage
var itemCount = localStorage.length;
console.log('Total items:', itemCount); // Output: Total items: 0
</script>

In this above example, we have displayed the complete set of methods and properties by using the localStorage object for demonstration. However, you can seamlessly substitute the sessionStorage object in place of the localStorage object to achieve similar functionality.


The localStorage Object

As mentioned previously, the localStorage object is used to store data without an expiration date, using key/value pairs. Each piece of data is associated with a key (e.g., 'first_name') and a corresponding value (e.g., 'Suresh'). For instance, the JavaScript code snippet below demonstrates this concept:

<script>
// Check if the localStorage object exists
if (localStorage) 
{
    // Store data
    localStorage.setItem("first_name", "Suresh");

    // Retrieve data
    alert("Hi, " + localStorage.getItem("first_name"));
} 
else {
    alert("Sorry, your browser do not support local storage.");
}
</script>

The above code confirms localStorage availability and attaches handlers to "Save" and "Access" buttons. Clicking "Save" uses localStorage.setItem() for storing the entered "first name", followed by a success alert. Clicking "Access" retrieves and displays the name using localStorage.getItem(), or alerts if none exists. If local storage isn't supported, an alert indicates this limitation.

To remove a specific item from storage, the removeItem() method can be used by passing the key name as an argument, such as localStorage.removeItem("first_name").

If you wish to clear the entire storage, you can utilize the clear() method, as in localStorage.clear(). It is important to exercise caution when using the clear() method as it will delete all key/value pairs from localStorage.

Note: It is worth noting that the data stored in web storage, both localStorage and sessionStorage, is not accessible across different browsers. For example, data stored in the Firefox browser will not be available in Google Chrome, Safari, Internet Explorer, or other browsers.

HTML local storage provides a reliable method for storing data within web applications. With HTML5 local storage functionality, developers can leverage the benefits of local storage over session storage, including data persistence and cross-browser support. It offers a convenient way to store and retrieve data, ensuring its availability and capacity within the local storage of the user's browser.


The sessionStorage Object

HTML5 sessionStorage offers a mechanism to store data on the client's side, similar to its sibling, localStorage. However, there is a key distinction: sessionStorage is scoped to the current session, which means the stored data persists only as long as the browser tab or window is open. When the user closes the tab or browser, the stored data is automatically cleared.

This makes session storage an ideal choice for scenarios that demand temporary storage for a specific user session. To gain a better understanding of how web storage works, let's explore the following example.

<script>
// Check if the sessionStorage object exists
if (sessionStorage) 
{
    // Store data
    sessionStorage.setItem("last_name", "Babu");

    // Retrieve data
    alert("Hi, " + localStorage.getItem("first_name") + " " + sessionStorage.getItem("last_name"));
} 
else {
    alert("Sorry, your browser do not support session storage.");
}
</script>

The above code checks for sessionStorage support, binds event handlers to "Save" and "Access" buttons, and lets users store "last_name". Upon clicking "Save", the "last_name" is stored via sessionStorage.setItem() and an alert confirms it. Clicking "Access" combines the stored "first_name" from localStorage with the retrieved "last_name" from sessionStorage, presenting it. If session storage isn't supported, an alert notifies users.

HTML session storage offers a reliable means of storing data within a user's session. When comparing session storage to local storage in HTML, session storage is advantageous in terms of its shorter lifespan and data sharing capabilities across tabs. By effectively managing data in HTML session storage, developers can optimize performance while considering security considerations. Additionally, session storage in HTML provides a specific capacity for storing data within the user's session, ensuring its availability and scope.


localStorage Vs sessionStorage

The main key differences are:

localStorage and sessionStorage are both mechanisms provided by HTML5 Web Storage that allow web developers to store data on the client's side. However, they have distinct differences in terms of scope, persistence, and use cases:

1. Scope:

  • localStorage: Data stored in localStorage is accessible across multiple windows and tabs of the same browser, as long as they belong to the same origin (i.e., same protocol, domain, and port).
  • sessionStorage: Data stored in sessionStorage is limited to the current browser tab or window. It cannot be accessed by other tabs or windows, even if they belong to the same origin.

2. Persistence:

  • localStorage: Data stored in localStorage persists even after the browser is closed or the user navigates away from the page. It remains until explicitly removed by the user or cleared programmatically.
  • sessionStorage: Data stored in sessionStorage only lasts for the duration of the current browser tab or window's session. It is automatically cleared when the session ends, typically when the tab or browser is closed.

3. Use Cases:

  • localStorage: It is suitable for scenarios where data needs to be stored semi-permanently and should be available across sessions. Examples include user preferences, cached data, and items in a shopping cart.
  • sessionStorage: It is ideal for storing temporary data that should be accessible within the current session, such as form data during multi-step processes, session-specific settings, and transient application state.

4. Sharing Data:

  • localStorage: Since data persists across sessions, it can be used to share data between different windows or tabs of the same origin.
  • sessionStorage: Data stored in sessionStorage is isolated to the current session, making it well-suited for keeping data private within a specific tab or window.

5. Data Cleanup:

  • localStorage: Data remains until explicitly removed by the user or cleared programmatically, making manual cleanup necessary.
  • sessionStorage: Data is automatically cleared when the session ends, reducing the need for explicit cleanup.

The choice between localStorage and sessionStorage depends on the scope and persistence requirements of your data. Use localStorage for data that needs to be available across sessions and tabs/windows, and use sessionStorage for data that should only be accessible within the current session or tab.


FAQ

What is HTML5 Web Storage?

HTML5 Web Storage is a web technology that allows web applications to store and retrieve data locally within a user's browser. It provides a way for web pages to store key-value pairs of data in a simple and efficient manner. This data persists even after the user navigates away from the page or closes the browser.

What are the two types of Web Storage?

There are two types of Web Storage: localStorage and sessionStorage.

  • localStorage: Data stored using localStorage is available across browser sessions and persists even after the browser is closed. The data remains stored until explicitly removed by the user or the web application.
  • sessionStorage: Data stored using sessionStorage is available only within the current browser tab or window. It is bound to the session and is cleared when the tab or window is closed.

How can you store data using Web Storage?

Storing data using Web Storage involves using the setItem() method provided by the localStorage or sessionStorage objects. Here's an example using localStorage:

// Storing data in localStorage
localStorage.setItem('username', 'john_doe');

How can you retrieve data from Web Storage?

Retrieving data from Web Storage is done using the getItem() method. Here's an example:

// Retrieving data from localStorage
const username = localStorage.getItem('username');
console.log('Username:', username);

Are there any data type limitations with Web Storage?

Yes, Web Storage can only store data as strings. This means that when you store non-string data types (e.g., numbers, objects), they will be automatically converted to strings. When retrieving data, you need to convert it back to the desired data type using functions like parseInt() or JSON.parse().

How much data can Web Storage store?

The amount of data that can be stored in Web Storage depends on the browser and the specific domain. Generally, localStorage provides more storage space compared to sessionStorage. The storage limit is usually around 5-10 MB per domain for localStorage. It's important to note that exceeding the storage limit can lead to exceptions being thrown.

How do you remove data from Web Storage?

Data can be removed from Web Storage using the removeItem() method. Here's an example:

// Removing data from localStorage
localStorage.removeItem('username');

What are some use cases for Web Storage?

Web Storage is useful for scenarios where you need to store small amounts of data locally within a user's browser. Some common use cases include:

  • Remembering User Preferences: Storing user preferences such as theme choices or language settings.
  • Caching Data: Storing frequently used data to reduce the need for repeated server requests.
  • Offline Mode: Storing data that users can access even when they're offline.
  • Shopping Carts: Storing items in a user's shopping cart so they persist between sessions.

What are the security considerations for Web Storage?

Web Storage operates in the context of the browser, and data stored in it can be accessed and manipulated by JavaScript code running on the same domain. This can be a security risk, as malicious scripts could potentially access sensitive information stored in Web Storage. Therefore, it's important not to store sensitive data like passwords or personal information in Web Storage.

Is Web Storage supported in all browsers?

Web Storage is supported in most modern browsers, including Chrome, Firefox, Safari, Edge, and Opera. However, it's always a good practice to check for compatibility before using any web technology, as some older browsers might not fully support it.

Can you give an example of using Web Storage to store and retrieve an object?

Certainly! When storing objects in Web Storage, you should first convert the object to a JSON string using JSON.stringify() before storing, and then parse it back using JSON.parse() when retrieving. Here's an example using localStorage:

// Storing an object in localStorage
const userObject = { name: 'Alice', age: 30 };
localStorage.setItem('user', JSON.stringify(userObject));

// Retrieving and parsing the object from localStorage
const storedUser = JSON.parse(localStorage.getItem('user'));
console.log('User:', storedUser); // { name: 'Alice', age: 30 }

How is Web Storage different from cookies?

Web Storage and cookies both allow you to store data locally, but they have several differences:

  • Size: Web Storage generally provides more storage space (around 5-10 MB) compared to cookies (typically limited to 4KB).
  • Performance: Web Storage is faster for accessing and retrieving data, as it's not sent to the server with each HTTP request like cookies are.
  • Expiration: Cookies can have expiration dates, while data in Web Storage persists until explicitly removed.
  • Accessibility: Cookies are sent to the server with every HTTP request, while Web Storage data stays on the client side and is not automatically sent to the server.
  • Security: Cookies can be set with different security attributes like secure and HttpOnly, making them more suitable for storing sensitive data.

Can Web Storage data be shared between different tabs or windows of the same browser?

Yes, data stored using localStorage can be accessed and shared across different tabs or windows of the same browser, as long as they are from the same domain. However, data stored using sessionStorage is confined to the specific tab or window where it was created and won't be accessible to other tabs or windows.

How do you check if Web Storage is supported in a user's browser?

You can check for Web Storage support using JavaScript. Here's an example:

if (typeof Storage !== 'undefined') {
  // Web Storage is supported
} else {
  // Web Storage is not supported
}

What happens if a user disables cookies in their browser?

Web Storage does not rely on cookies, so it remains functional even if a user disables cookies in their browser. However, keep in mind that Web Storage also has its own limitations, such as the storage size and domain-specific accessibility.

Is there a way to listen for changes in Web Storage data?

Unfortunately, Web Storage does not provide built-in mechanisms for listening to changes. You would need to implement a custom solution using techniques like the StorageEvent API, which can help you detect changes made to Web Storage data in other tabs or windows of the same domain.

Does Web Storage work in private browsing or incognito mode?

Yes, Web Storage is available in private browsing or incognito mode. However, the behavior might vary slightly between browsers. Data stored in localStorage will persist across sessions even in private mode until the browser cache is cleared, while sessionStorage data will still be limited to the current private browsing session.

Can Web Storage data be shared between different domains?

No, Web Storage data is domain-specific. Data stored in Web Storage is accessible only from pages within the same domain. Different domains have their own separate storage spaces, preventing cross-domain data sharing.

Can Web Storage be used for large files, such as images or videos?

Web Storage is not designed for storing large files like images or videos due to its storage limitations and performance considerations. It's better to use other technologies like server-side storage, Content Delivery Networks (CDNs), or the browser's built-in caching mechanisms for handling large files.

How can you clear all the data stored in Web Storage?

You can clear all data stored in localStorage using the clear() method:

// Clear all data in localStorage
localStorage.clear();

Remember that this will remove all data stored under the current domain in localStorage. Similarly, you can use sessionStorage.clear() to clear all data in sessionStorage.

What happens to Web Storage data when a user clears their browser's cache?

When a user clears their browser's cache, Web Storage data stored using localStorage is generally not affected and remains intact. However, data stored in sessionStorage is tied to the browser session, so it will be cleared along with the session data.

Can Web Storage data persist across different websites within the same domain?

Yes, Web Storage data is shared across different pages and resources served from the same domain. This can be beneficial for maintaining a consistent user experience across different parts of a website.

Is there any way to set an expiration time for data stored in Web Storage?

Web Storage itself does not provide built-in mechanisms for setting expiration times. If you need data to expire after a certain time, you would need to manage this manually by storing a timestamp alongside the data and periodically checking and removing expired data.


Conclusion

HTML web storage provides a convenient and efficient method for storing data locally on the user's computer. With the localStorage object, data can be stored indefinitely, while the sessionStorage object allows for temporary storage during a single session. The key-value pair structure simplifies data organization and retrieval. Web storage offers advantages over traditional cookies, including larger data storage capacity and faster performance. However, it is important to consider that web storage is not secure and should not be used for sensitive information. By understanding the capabilities and limitations of web storage, developers can leverage this feature to enhance the user experience and create more dynamic and personalized web applications.