How to store data in the browser with the HTML5 localStorage API?

HTML5 localStorage is a web storage API that allows you to store data directly in the user's browser. Unlike sessionStorage, which expires when the browser tab is closed, localStorage data persists indefinitely until explicitly removed by the user or the application.

The localStorage API provides a simple way to store key-value pairs as strings in the browser. This feature is particularly useful for saving user preferences, form data, application state, or any data that should persist across browser sessions.

Syntax

Following is the syntax for storing data in localStorage −

localStorage.setItem(key, value);
localStorage.key = value;

Following is the syntax for retrieving data from localStorage −

var data = localStorage.getItem(key);
var data = localStorage.key;

Following is the syntax for removing data from localStorage −

localStorage.removeItem(key);
localStorage.clear(); // removes all items

Basic localStorage Operations

The localStorage API provides several methods to manage stored data. The most commonly used methods are setItem(), getItem(), removeItem(), and clear().

Example − Basic Storage Operations

<!DOCTYPE html>
<html>
<head>
   <title>localStorage Basic Operations</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>localStorage Basic Operations</h2>
   <button onclick="storeData()">Store Data</button>
   <button onclick="retrieveData()">Retrieve Data</button>
   <button onclick="removeData()">Remove Data</button>
   <button onclick="clearAll()">Clear All</button>
   <p id="result"></p>

   <script>
      function storeData() {
         localStorage.setItem("username", "JohnDoe");
         localStorage.setItem("email", "john@example.com");
         document.getElementById("result").innerHTML = "Data stored successfully!";
      }

      function retrieveData() {
         var username = localStorage.getItem("username");
         var email = localStorage.getItem("email");
         document.getElementById("result").innerHTML = 
            "Username: " + username + "<br>Email: " + email;
      }

      function removeData() {
         localStorage.removeItem("username");
         document.getElementById("result").innerHTML = "Username removed!";
      }

      function clearAll() {
         localStorage.clear();
         document.getElementById("result").innerHTML = "All data cleared!";
      }
   </script>
</body>
</html>

The example demonstrates storing, retrieving, removing, and clearing localStorage data. Click the buttons to see how each operation works.

Persistent Hit Counter

One common use case for localStorage is creating a persistent counter that maintains its value across browser sessions.

Example

<!DOCTYPE html>
<html>
<head>
   <title>localStorage Hit Counter</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px; text-align: center;">
   <h2>Page Visit Counter</h2>
   <div id="counter" style="font-size: 24px; color: #007bff; margin: 20px 0;"></div>
   <p>Refresh the page to increase the counter.</p>
   <p>Close the browser and reopen to see the counter persist.</p>
   <button onclick="resetCounter()">Reset Counter</button>

   <script>
      if (localStorage.hits) {
         localStorage.hits = Number(localStorage.hits) + 1;
      } else {
         localStorage.hits = 1;
      }
      
      document.getElementById("counter").innerHTML = 
         "Total visits: " + localStorage.hits;

      function resetCounter() {
         localStorage.removeItem("hits");
         location.reload();
      }
   </script>
</body>
</html>

The counter increments each time the page loads and persists even after closing the browser. The reset button demonstrates removing specific localStorage items.

Storing Complex Data

Since localStorage only stores strings, complex data like objects and arrays must be converted to JSON format using JSON.stringify() for storage and JSON.parse() for retrieval.

Example − Storing JSON Data

<!DOCTYPE html>
<html>
<head>
   <title>localStorage with JSON</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Storing User Preferences</h2>
   <form id="prefsForm">
      <label>Theme: 
         <select name="theme">
            <option value="light">Light</option>
            <option value="dark">Dark</option>
         </select>
      </label><br><br>
      <label>Language: 
         <select name="language">
            <option value="en">English</option>
            <option value="es">Spanish</option>
            <option value="fr">French</option>
         </select>
      </label><br><br>
      <button type="button" onclick="savePreferences()">Save Preferences</button>
      <button type="button" onclick="loadPreferences()">Load Preferences</button>
   </form>
   <p id="status"></p>

   <script>
      function savePreferences() {
         var form = document.getElementById("prefsForm");
         var preferences = {
            theme: form.theme.value,
            language: form.language.value,
            savedAt: new Date().toISOString()
         };
         
         localStorage.setItem("userPrefs", JSON.stringify(preferences));
         document.getElementById("status").innerHTML = "Preferences saved!";
      }

      function loadPreferences() {
         var stored = localStorage.getItem("userPrefs");
         if (stored) {
            var preferences = JSON.parse(stored);
            var form = document.getElementById("prefsForm");
            form.theme.value = preferences.theme;
            form.language.value = preferences.language;
            document.getElementById("status").innerHTML = 
               "Preferences loaded! Saved on: " + new Date(preferences.savedAt).toLocaleDateString();
         } else {
            document.getElementById("status").innerHTML = "No preferences found.";
         }
      }

      // Load preferences on page load
      loadPreferences();
   </script>
</body>
</html>

This example shows how to store and retrieve complex user preference objects using JSON serialization. The preferences are automatically loaded when the page opens.

localStorage vs sessionStorage localStorage Persists until manually cleared Available across browser tabs Survives browser restart Storage limit: ~5-10MB Domain-specific sessionStorage Expires when tab is closed Tab-specific storage Lost on browser restart Storage limit: ~5-10MB Domain-specific

Error Handling with localStorage

localStorage operations can fail due to storage quota exceeded, browser privacy settings, or incognito mode. Always wrap localStorage operations in try-catch blocks for robust error handling.

Example − Safe localStorage Usage

<!DOCTYPE html>
<html>
<head>
   <title>Safe localStorage Usage</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Safe localStorage Operations</h2>
   <button onclick="testStorage()">Test Storage Availability</button>
   <button onclick="safeSave()">Safe Save Data</button>
   <p id="output"></p>

   <script>
      function isStorageAvailable() {
         try {
            var test = 'test';
            localStorage.setItem(test, test);
            localStorage.removeItem(test);
            return true;
         } catch (e) {
            return false;
         }
      }

      function testStorage() {
         var available = isStorageAvailable();
         document.getElementById("output").innerHTML = 
            "localStorage available: " + available;
      }

      function safeSave() {
         try {
            if (isStorageAvailable()) {
               localStorage.setItem("safeData", "This data was saved safely!");
               var retrieved = localStorage.getItem("safeData");
               document.getElementById("output").innerHTML = 
                  "Success: " + retrieved;
            } else {
               document.getElementById("output").innerHTML = 
                  "localStorage is not available.";
            }
         } catch (error) {
            document.getElementById("output").innerHTML = 
               "Error saving data: " + error.message;
         }
      }
   </script>
</body>
</html>

This example demonstrates how to safely check localStorage availability and handle potential errors when storing data.

Browser Compatibility and Limitations

localStorage is supported in all modern browsers including Chrome 4+, Firefox 3.5+, Safari 4+, and Internet Explorer 8+. However, there are some important limitations to consider −

  • Storage Limit − Most browsers limit localStorage to 5-10MB per domain.

  • String Only − Only strings can be stored directly; objects need JSON conversion.

  • Synchronous API − localStorage operations are blocking and can impact performance with large data.

  • Same-Origin Policy − Data is only accessible to the same protocol, host, and port.

  • Not Available in Workers − localStorage cannot be used in web workers.

Feature localStorage sessionStorage Cookies
Storage Capacity 5-10MB 5-10MB 4KB
Lifetime Until manually cleared Until tab closes Set expiration date
Sent to Server No No Yes (automatic)
Accessibility Any tab, same origin Same tab only Any tab, same origin
API JavaScript only JavaScript only JavaScript + HTTP headers

Conclusion

HTML5 localStorage

Updated on: 2026-03-16T21:38:53+05:30

300 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements