Published Nov 4, 2023 ⦁ 5 min read

Master Local Storage in JavaScript

Introduction to Local Storage

Local storage allows web applications to store data client-side in the browser. This enables powerful offline capabilities, boosts performance by reducing server requests, and gives web apps abilities previously only available to native apps.

With localStorage, web apps can persist user preferences, cache API responses, enable offline functionality, store game state, and more - all without relying on a server connection. The storage limit per origin is generous at around 5MB or more depending on the browser, far greater than what cookies allow.

Local storage is widely supported in modern browsers like Chrome, Firefox, Safari, and Edge. There are even polyfills available to enable localStorage in older browsers.

At its core, localStorage uses simple key-value pairs. You can store any values as strings natively, and serialize rich data structures like objects and arrays using JSON.stringify(). This allows you to leverage localStorage for app state, user settings, form data, and other structured data persistence.

Compared to cookies, localStorage offers much more storage space and direct JavaScript access. However, cookies can still be useful for non-JS environments, server-side usage, and cross-origin/subdomain scenarios.

Key Use Cases for Local Storage

Here are some of the most common use cases and examples for leveraging local storage in web apps:

  • Persist user settings and preferences - Store things like custom themes, layouts, language, etc. for a personalized experience.
  • Cache API responses - Local storage can serve as a speedy front-end cache to boost performance and work offline.
  • Enable offline functionality - Apps can load core data from localStorage if the network is down. Sync back to server when possible.
  • Store game state - Local storage provides expanding storage for immersive, progressive web games.
  • Shopping carts - Serialize cart data locally to persist across sessions and devices.
  • Form data - Avoid lost form data by caching locally before submit. Especially helpful for long, multi-page forms.

There are many other niche scenarios, but those cover some of the most popular uses. Local storage opens up native-like abilities to web apps.

Local Storage vs Cookies

Local storage and cookies can both persist data in the browser, but have some key differences:

  • Capacity - Cookies are limited to 4KB, localStorage offers at least 5MB or more of space.
  • Accessibility - localStorage is only accessible via JavaScript, while cookies are sent with every HTTP request.
  • Expiry - Cookies can expire, localStorage data persists until explicitly deleted.
  • Scope - localStorage is scoped per origin, cookies are available cross-origin.
  • Usability - Cookies are easier to use in non-JS environments. localStorage requires JavaScript.

So in summary, localStorage provides greater capacity and direct scripting access, but cookies are better for server-side usage and non-JS support. Use cookies for cross-origin needs as well.

localStorage API Methods

The localStorage API exposes simple methods to interact with stored data:

  • setItem() - Store data with key/value pair
  • getItem() - Retrieve data by key
  • removeItem() - Delete data by key
  • clear() - Delete all stored data
  • key() - Get key at provided index
  • length - Get total number of stored keys

It has a simple key/value store api similar to a Map. You can treat it a bit like a persistent dictionary in your code.

Serializing Data in localStorage

Only strings can be stored natively in localStorage. But you can leverage JSON.stringify() to serialize rich object and array data structures as strings.

For example:

// Object to store
const data = {
  name: 'John',
  age: 30, 
  hobbies: ['coding', 'climbing']
};

// Serialize to JSON string
const json = JSON.stringify(data);

// Store serialized object 
localStorage.setItem('user', json);

// Retrieve and parse back to object
const userData = JSON.parse(localStorage.getItem('user'));

This allows you to take full advantage of the available storage for app state, user settings, form data, and other structured data storage needs.

Local Storage Tips and Tricks

Here are some best practices and advanced techniques for working with localStorage:

  • Namespace keys - Prefix keys like 'app_' + keyName to avoid collisions.
  • Handle quota limits - Watch for QUOTA_EXCEEDED_ERR. Cleanup and batch write.
  • Use libraries - localForage provides nicer API and fallbacks.
  • Clear stale data - Clean up unused keys to avoid stale data issues.
  • Handle tabs - Account for multiple open tabs overriding data.

Offline Shopping Cart Example

Here is an example utilizing localStorage for an offline shopping cart:

// Cart data array
const cart = []; 

// Serialize and store cart in localStorage 
localStorage.setItem('cart', JSON.stringify(cart));

// Add item
cart.push({
  id: 'p1',
  name: 'Product 1',
  price: 9.99
});

// Update localStorage
localStorage.setItem('cart', JSON.stringify(cart));

// Checkout when online
async function checkout() {
  // Send cart data to server
  await sendCartToServer(cart);
  
  // Clear localStorage
  localStorage.clear(); 
}

This allows the cart to persist locally across sessions and work offline. The cart can be synced with the server when back online.

Conclusion

Local storage opens up offline capabilities and performance benefits by persisting data client-side. With proper usage, it can enable many powerful scenarios for web apps.

The simple API makes localStorage easy to leverage for developers. Make sure to follow best practices around namespacing, handling quota limits, and clearing stale data.

LocalStorage unlocks abilities previously only available to native apps right in the web browser. If you're building a web app that could benefit from offline support or performance boosts, be sure to consider leveraging localStorage. The team at DevHunt can help showcase developer tools that integrate local storage capabilities.