Published Nov 6, 2023 ⦁ 5 min read

Store Data Locally with JavaScript localStorage

Introduction to localStorage in JavaScript

localStorage javascript allows data to be stored locally in the browser, useful for persisting data between page loads without needing a server. In this post, we'll cover the basics of using localStorage, best practices, and examples of common use cases.

Specifically, we'll look at:

  • How to check browser support and use basic localStorage methods
  • Saving and retrieving JavaScript objects with JSON
  • When to use localStorage vs cookies
  • Security and performance considerations
  • localStorage use cases like offline capability, caching, state management

localStorage gives web developers expanded options for client-side data storage that persists between sessions. Compared to cookies, it allows significantly more data to be stored (at least 5MB vs 4KB) and is only accessible via JavaScript, not sent to the server with every request which improves security.

Let's dive in and see how we can harness the power of localStorage in JavaScript!

localStorage Basics and Usage

localStorage is supported in all modern browsers, but it's good practice to check for support before using it:

if (typeof(Storage) !== "undefined") {
  // localStorage is available
} else {
  // No web storage support  
}

The localStorage API exposes simple getItem, setItem, removeItem, and clear methods. Here's an example usage:

// Store data
localStorage.setItem("name", "John");

// Retrieve data  
const name = localStorage.getItem("name");

// Remove saved data
localStorage.removeItem("name"); 

// Clear all localStorage
localStorage.clear();

Data saved with localStorage persists until explicitly cleared. sessionStorage is cleared when the browser tab is closed.

localStorage can only store string values. To store objects, serialize with JSON:

const user = {name: "John", age: 30};

// Save object
localStorage.setItem("user", JSON.stringify(user));

// Get object
const userJson = localStorage.getItem("user");
const user = JSON.parse(userJson); 

Be aware of potential quota exceeded errors if saving too much data. Handle gracefully by catching the exception or cleaning up unused localStorage items.

Saving and Retrieving JavaScript Objects

While localStorage only stores strings natively, we can serialize JavaScript objects as JSON to enable rich data storage.

For example, a TODO list app like Microsoft To Do could use localStorage to persist TODO items between sessions without needing a server.

Let's look at an example of saving and retrieving a TODO item object:

const todoItem = {
  text: "Finish localStorage article",
  completed: false 
};

// Serialize object to JSON string
const todoJson = JSON.stringify(todoItem);

// Save object
localStorage.setItem("todo", todoJson);

// Retrieve stored string
const storedTodoJson = localStorage.getItem("todo");

// Deserialize JSON string to original object 
const storedTodo = JSON.parse(storedTodoJson);

This allows us to persist complex data structures while avoiding the need to encode/decode the values ourselves.

There are also utilities like jStorage that build on localStorage and handle serializing objects for you. But native JSON methods work quite well.

localStorage Use Cases and Examples

There are many useful applications for localStorage in web development:

  • Persist user settings/preferences - Store user configured options locally
  • Shopping carts - Avoid needing a server by saving cart data locally. Sites like StackCommerce use this.
  • Caching - Store API responses to avoid network requests. Hacker News uses localStorage caching.
  • Application state - Persist state between sessions. Jira uses localStorage for this.
  • Offline capability - Local data as a fallback when offline. Twitter Lite enables basic tweets offline.

For example, an application could cache API data to both speed up performance and enable limited offline access:

// Make initial network request
fetch('/api/data')
  .then(response => response.json())
  .then(data => {
    // Cache response  
    localStorage.setItem('cachedData', JSON.stringify(data));
    
    // Use data
  })
  .catch(() => {
    // Get cached data if fetch failed  
    const dataJson = localStorage.getItem('cachedData');
    const data = JSON.parse(dataJson);
    
    // Use cached data
  });

Combined with service workers, localStorage enables true offline capability. Sites like Squoosh demonstrate this in practice.

Best Practices for localStorage

While localStorage is very useful, there are some best practices worth keeping in mind:

  • Use meaningful keys for saved data
  • Handle "quota exceeded" errors gracefully
  • Only store necessary data - minimize bloat
  • Clear localStorage manually when no longer needed
  • Use selectively for appropriate use cases
  • Combine with service workers for robust offline capability

Security:

  • localStorage data can be read by any scripts on the page. Never store sensitive data.
  • Use encryption if needed to protect stored data.
  • localStorage is vulnerable to XSS attacks exposing data.

Performance:

  • Access localStorage asynchronously to avoid blocking
  • Limit storing large amounts of data. 5-10MB is a good guideline.
  • Watch for outdated stale data in caches
  • Judiciously apply localStorage caching

Alternatives:

  • cookies - limited storage but sends data to server
  • IndexedDB - better access control and storage limits
  • Browser extensions for enhanced storage APIs
  • Cloud services like Firebase for remote storage

Summary of Key Points

  • localStorage javascript allows persisting data locally in the browser across page loads, unlocking many useful capabilities like caching, preferences, offline access, and shopping carts.
  • The API exposes simple synchronous methods like getItem and setItem to store and retrieve string key/value pairs.
  • Serializing objects to JSON enables rich data structures to be stored for later retrieval.
  • Common use cases include improving performance through caching, retaining application state, and enabling basic offline capability when combined with service workers.
  • Security, performance, and alternative options like IndexedDB should be considered when leveraging localStorage.
  • Overall, localStorage is a powerful client-side storage tool for web developers when applied judiciously. It unlocks many creative possibilities for enhancing websites and applications.

For more on harnessing the power of localStorage and other techniques for supercharging your web apps, check out DevHunt's featured open source tools and tutorials.