Local Storage

Local Storage is a part of the Web Storage API, which allows you to store data locally within the user's browser. Local Storage is a simple key-value storage system that persists data even after the browser is closed. It can be a useful alternative to cookies for storing data that doesn't need to be sent to the server with every request.

Here's an example of how to use Local Storage:

<!DOCTYPE html>
  <title>Local Storage Example</title>
  <input type="text" id="inputText" placeholder="Enter some text">
  <button onclick="saveText()">Save</button>
  <button onclick="loadText()">Load</button>
  <p id="display"></p>

    function saveText() {
      const text = document.getElementById("inputText").value;
      localStorage.setItem("savedText", text);

    function loadText() {
      const savedText = localStorage.getItem("savedText");
      document.getElementById("display").innerHTML = savedText;

In this example, there are two buttons: "Save" and "Load". When the user clicks the "Save" button, the `saveText()` function is called. This function retrieves the value of the input field and saves it in Local Storage using the `setItem()` method.

When the user clicks the "Load" button, the `loadText()` function is called. This function retrieves the saved text from Local Storage using the `getItem()` method and displays it on the page.

Local Storage has several advantages over cookies:

  1. More storage capacity: Local Storage can store up to 5-10 MB of data per domain, while cookies are limited to about 4 KB.
  2. Better performance: Local Storage data is not sent to the server with each request, which can reduce bandwidth usage and improve performance.
  3. Simpler API: The Web Storage API provides simple methods like `getItem()`, `setItem()`, `removeItem()`, and `clear()` to interact with the data, making it easier to work with compared to cookies.

However, it's important to note that Local Storage should not be used for sensitive data, as it is stored unencrypted on the user's device and can be accessed by other scripts on the same domain. For sensitive data, consider using secure cookies or other more secure methods of data storage.

Was this page helpful?