Web storage

Lord AbiollaLord Abiolla
6 min read

Web storage refers to the mechanisms that allow websites and web applications to store data directly in the user’s browser.

It allows for faster and more efficient data retrieval, eliminating the need for constant communication with the server. Moreover, it’s secure and more private compared to other forms of storage, as data is stored in the client’s computer and can only be accessed by the website that created it.


Types of Web storage

There are two main types of Web storage which include;

  1. Local storage

  2. Session storage

  1. Local Storage

Local storage is part of web storage API that allow you store data persistently in the user’s browser.

The data here remains persistent even after the browser is closed and reopened, making it powerful for storing data across multiple sessions. Moreover, data here is stored as key-value pairs with both keys and values being strings.

The local storage is a part of the global window object, and therefore, localStorage is the same as window.localStorage.

The local storage object can be deleted only on instances when the data gets deleted by JavaScript or when the browser’s cache gets cleared.

Some key features of local storage include:

  • Persistent storage.

  • Data is stored per domain.

  • Can store up to 5 - 10 MB which’s much larger than cookies.

Some of the use cases of local storage include:

  • Saving user preferences such as themes and layout choices.

  • Caching data for online use

  • Storing game progress data in browser-based games.

  1. Session Storage

Sessions stores data only for the duration of browser session. Once the browser or tab is closed, the data also gets cleared.

Session storage also stores data in key-value pairs with both keys and values being string.

Some key features of session storage include the following;

  • Temporary storage

  • Separate storage for each browser tab.

  • Same size limit as local storage (5 MB).

Some of the use cases of session storage include;

  • Storing data during checkout process.

  • Keeping form data while navigating through the same session.

  • Tracking user activity on a single tab.

How to Access the Web storage

There are two main ways of accessing the web storage.

  1. Using the same technique for accessing the regular JavaScript object. i.e., using the dot notation or the bracket notation as used to access JavaScript object.

  2. Using the built-n web storage methods or interfaces.

Built-in Web storage methods

Both localStorage and sessionStorage are instances of the storage interface, and they share the same built-in methods for data manipulation.

Some of these built-in methods include the following:

  1. The setItem() method

The setItem() method stores a key–value pair in web storage (either localStorage or sessionStorage). Both the key and the value are stored as strings.

If the specified key already exists, setItem() overwrites its value.

Non-string values (numbers, objects, boolean) are automatically converted to strings before storage.

It accepts two arguments:

  • key – the name under which the value will be stored.

  • value – the data to store (will be converted to a string).

Example

// Local Storage
localStorage.setItem("username", "Lord");
localStorage.setItem("age", 25);

// Session Storage
sessionStorage.setItem("sessionID", "abc123");
  1. The getItem() method

The getItem() method retrieves the value for the given key.

If the specified key does not exist, it returns a null.

It accepts one argument :

  • key - the name under which the value will be stored.

Example

let name = localStorage.getItem("username"); // "Lord"
let age = localStorage.getItem("age"); // "25"

let sessionID = sessionStorage.getItem("sessionID"); // "abc123"

An example of storing and retrieving data from a local storage.

let user = { name: "Lord", country: "Kenya" };

// Store as JSON string
localStorage.setItem("user", JSON.stringify(user));

// Retrieve and parse back into object
let retrievedUser = JSON.parse(localStorage.getItem("user"));
console.log(retrievedUser);

Output

  1. The removeItem() method

This method is used to remove the specified key and its value from the storage.

If the key does not exist, it returns nothing.

It accepts one argument, which is the key to be removed.

Example

localStorage.removeItem("username");
sessionStorage.removeItem("sessionID");
  1. The clear() method

The clear() method removes all the stored data for that storage object.

clear() leaves the storage completely empty and therefore, should be used with caution as you cannot selectively exclude keys.

Example

localStorage.clear(); // Deletes all local storage for this domain
sessionStorage.clear(); // Deletes all session storage for this session
  1. The length() method

length() method is used to return the total number of items stored in the storage.

Example

console.log(localStorage.length); // e.g., 2
console.log(sessionStorage.length); // e.g., 1
  1. The key() method

The key() method is used to retrieve key name at the given numeric index.

The index is zero-based and order of keys is browser-dependent.

Example

localStorage.setItem("a", 1);
localStorage.setItem("b", 2);

console.log(localStorage.key(0)); // "a" or "b" (order may vary)

Practical examples

  1. Remembering user’s theme preference

// Save theme
function saveTheme(theme) {
    localStorage.setItem("theme", theme);
}

// Load theme
function applyTheme() {
    let theme = localStorage.getItem("theme");
    if (theme) {
        document.body.className = theme;
    }
}

// On page load
applyTheme();

// When user changes theme
document.getElementById("theme-toggle").onclick = function() {
    let newTheme = document.body.className === "dark" ? "light" : "dark";
    saveTheme(newTheme);
    applyTheme();
};
  1. Temporary shopping cart

// Add item to cart (session-based)
function addToCart(item) {
    let cart = JSON.parse(sessionStorage.getItem("cart")) || [];
    cart.push(item);
    sessionStorage.setItem("cart", JSON.stringify(cart));
}

// Get cart items
function getCart() {
    return JSON.parse(sessionStorage.getItem("cart")) || [];
}

// Example usage
addToCart({ id: 1, name: "Laptop", price: 1200 });
console.log(getCart());
  1. Counting page visits

let visits = localStorage.getItem("visits");

if (!visits) {
    visits = 1;
} else {
    visits = parseInt(visits) + 1;
}

localStorage.setItem("visits", visits);

console.log(`You have visited this page ${visits} times.`);

Limitations and Security concerns of Web Storage

  1. Storage Limit: One of the main limitations of Web Storage is the amount of data it can store. Most modern browsers allow up to 5MB of data per domain. This is significantly more than the 4KB limit of cookies, but it may still not be enough for some applications.

  2. No Data Protection: Web Storage does not provide any built-in data protection. All data is stored as plain text, which can be a security risk. If an attacker can run JavaScript on your website, they can access all data stored in Web Storage.

  3. Same Origin Policy: Web Storage follows the same origin policy. This means that data stored by a script on one domain cannot be accessed by a script on another domain. While this is a good security feature, it can also be a limitation if you need to share data across different domains.

  4. No Server Communication: Unlike cookies, data stored in Web Storage is never sent to the server. This can be both an advantage and a disadvantage, depending on your needs. On one hand, it can improve performance by reducing the amount of data sent with each HTTP request. On the other hand, it means that the server has no direct access to the data stored in Web Storage.

  5. User Control: Users have full control over Web Storage. They can view, modify, and delete the data at any time. This can be a problem if your application relies on the data being consistent. To mitigate these limitations and security concerns, it's important to use Web Storage responsibly.


Conclusion

Some of the key points to remember include the following;

  • Values are always stored as strings.

  • To store objects or arrays, use JSON.stringify() and retrieve them with JSON.parse().

  • Data is domain-specific — storage from one site can’t be accessed by another.

  • Local storage persists indefinitely unless cleared by the user or code.

  • Session storage ends when the browser tab is closed.

  • Do not store sensitive data (e.g., passwords, tokens) in web storage.

10
Subscribe to my newsletter

Read articles from Lord Abiolla directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Lord Abiolla
Lord Abiolla

Passionate Software Developer with a strong enthusiasm for data, technology, and entrepreneurship to solve real-world problems. I enjoy building innovative digital solutions and currently exploring new advancements in data, and leveraging my skills to create impactful software solutions. Beyond coding, I have a keen interest in strategic thinking in business and meeting new people to exchange ideas and collaborate on exciting projects.