What is Web Storage in JavaScript: Benefits, Precautions, and Examples

Javascript, when it comes to client-side data storage, has some of the best features that help developers create browser databases. Web storage, which consists of LocalStorage and SessionStorage, is targeted to help retain and manage information between sessions and page refresh. In this article, we are going to learn about what is web storage, its advantages, its usage warnings, as well as its practical applications for a smoother learning curve.

What is Web Storage?

Web storage is an HTML5 feature that enables web applications to keep data within the user’s browser. This data has persistence and can be accessed even if the web browser is opened and closed. There are two types of Web Storage:

  • LocalStorage: This is where data saved does not expire. The data stays forever until someone deletes it.
  • SessionStorage: This is a web storage limit on real-time sessions, which means when the page session on a window or a tab remains, the data remains saved . This is deleted when the page session is terminated (for instance, the page is closed).

LocalStorage

LocalStorage serves to retain data that is intended for retention beyond one browser session. It is useful for data that has to be accessed even after the current user session is terminated and the browser is closed. Some typical use cases of LocalStorage are described below:

  • User Preferences: Saving selected options by a user, for instance, which theme to use (light/dark mode), which language is on the page, and so on.
  • Persistent Form Data: Saving and restoring people’s input on a form so that they do not lose the progress that they have already made when, for example, the browser is accidentally closed.
  • Shopping Carts: Most e-commerce applications provide the ability to save items in a shopping cart, this function is often migratable to allow the user to restore their previous cart without a session.
  • Offline Applications: Saving information in a form that is not connected to the network, such as notes and documents, and can easily be called up even when the user shuts the browser down then opens it again.
  • Authentication Tokens: Safe practices will discourage the storage of more sensitive information, especially in LocalStorage. Some apps, however, will use this non-sensitive storage in a way that, for example, some tokens or IDs useful in separating users in future sessions will be stored.

Storing Data in LocalStorage:

// Storing data  
localStorage.setItem('username', 'JohnDoe');  
localStorage.setItem('theme', 'dark');  
  
// Retrieving data  
const username = localStorage.getItem('username');  
const theme = localStorage.getItem('theme');  
  
console.log(username); // Output: JohnDoe  
console.log(theme);    // Output: dark  
  
// Removing data  
localStorage.removeItem('username');  
  
// Clearing all data  
localStorage.clear();  

SessionStorage

SessionStorage is used to store information related to a user for a particular page session. All the data therein will be removed when the page session ends which could be, locking of the browser by the user. Here are some common scenarios where SessionStorage is beneficial:

  • Temporary Form Data: caching, which can temporarily store form inputs within one session to prevent data loss during user errors like page navigation.
  • Single-Session Authentication: Permanent session tokens or state should not persist beyond the session. Examples are tokens for answers provided in CAPTCHAs or temporary access tokens stored within a session.
  • Page-Oriented State: Any state that is relevant to a single page/tab; for example, those that constituents will expect to disappear once the page is refreshed or the tab closed, such as UI states (e.g. expanded/collapsed panels)
  • Wizard or Multi-Step Forms: Holding data for instances, especially for multi-step forms or wizards, where you only expect such data to be held available until the user is done with the process or closes the tab.

Storing Data in SessionStorage:

// Storing data  
sessionStorage.setItem('sessionID', 'abc123');  
sessionStorage.setItem('cartItems', JSON.stringify(['item1', 'item2', 'item3']));  
  
// Retrieving data  
const sessionID = sessionStorage.getItem('sessionID');  
const cartItems = JSON.parse(sessionStorage.getItem('cartItems'));  
  
console.log(sessionID); // Output: abc123  
console.log(cartItems); // Output: ['item1', 'item2', 'item3']  
  
// Removing data  
sessionStorage.removeItem('sessionID');  
  
// Clearing all data  
sessionStorage.clear();

Benefits of Using Web Storage

  • Ease: The Web Storage API is very clear and uncomplicated that even the most novice of web developers will use it without much difficulty.
  • Volume: There is a size limitation of LocalStorage and SessionStorage of 5MB per origin, and that’s a lot when compared to cookies.
  • Speed: Web Storage allows the user to cache data and thus prevents redundant requests from the same data, increasing loading speed and better performance.
  • Safety: Web Storage has more safety than cookies, in particular because they are not included as part of every HTTP request made which increases the chances of data leakage.
  • Versatility: It is possible to use Web Storage in different level of applications, varying from basic form input data preservation through to advanced state management in single page applications.

Precautions When Using Web Storage

  • Data Sensitivity: Do not store sensitive data (e.g., passwords, credit card information) in web storage since that information is accessible through JavaScript in the browser.
  • Storage Limits: Ensure that you keep within the storage limits (often 5MB per origin) to decrease the risk of reaching the quota since this could result in errors.
  • Browser Compatibility: Check that the browsers of the intended audience allow Web Storage usage (which most up-to-date browsers do).
  • Data Consistency: Data synchronization, especially in a situation involving multiple tabs updating data simultaneously, must be done carefully.
  • Security Practices: Follow best security practices like encryption and validation to reduce exposure from potential XSS attacks.

Let’s assume you provide a web application allowing users to switch views from light to dark modes. You can remember the user’s last selected mode using LocalStorage even after they log out.

HTML:

<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <meta name="viewport" content="width=device-width, initial-scale=1.0">  
    <title>Theme Switcher</title>  
    <style id="theme-style">  
        /* Default light theme */  
        body {  
            background-color: white;  
            color: black;  
        }  
    </style>  
</head>  
<body>  
    <button id="theme-button">Switch Theme</button>  
  
    <script src="theme-switcher.js"></script>  
</body>  
</html>  

JavaScript (theme-switcher.js):

document.addEventListener('DOMContentLoaded', () => {  
    const themeButton = document.getElementById('theme-button');  
    const themeStyle = document.getElementById('theme-style');  
  
    // Load saved theme from LocalStorage  
    const savedTheme = localStorage.getItem('theme');  
    if (savedTheme) {  
        applyTheme(savedTheme);  
    }  
  
    // Switch theme on button click  
    themeButton.addEventListener('click', () => {  
        const currentTheme = themeStyle.innerHTML.includes('white') ? 'dark' : 'light';  
        applyTheme(currentTheme);  
        localStorage.setItem('theme', currentTheme);  
    });  
  
    function applyTheme(theme) {  
        if (theme === 'dark') {  
            themeStyle.innerHTML = `  
                body {  
                    background-color: black;  
                    color: white;  
                }  
            `;  
        } else {  
            themeStyle.innerHTML = `  
                body {  
                    background-color: white;  
                    color: black;  
                }  
            `;  
        }  
    }  
});  

To elaborate further, a user’s requested theme will be saved in LocalStorage so that it can be used to apply the requested theme every time the page is loaded.

Conclusion

JavaScript Web Storage is one of the features that should be taken full advantage of since it will in one way or the other optimize the application web users experience. Appreciate the merits, observe the rules, and give the hand on the practical instances to be able to exploit LocalStorage and SessionStorage appropriately in your projects. Be it through maintaining user preferences, handling temporary data or keeping data cached Web Storage has got you solved the problem in an elegant and effective manner.

Happy Coding for All Javascript Developers!

Web Storage
  1. MDN Web Docs (Mozilla Developer Network)

Leave a Reply

Your email address will not be published. Required fields are marked *

×