Learn JavaScript Β· 12/15

Browser Storage: Remembering Data Across Sessions

6 min read

Hey there, future JavaScript wizard! πŸ§™β€β™‚οΈ Ever wonder how websites remember your username, the items in your shopping cart, or that you prefer dark mode, even after you've closed the tab and taken a nap? The magic lies in Browser Storage.

πŸ€” The Problem: Websites Have Terrible Memory

Imagine you're having a conversation with a friend who has the memory of a goldfish. You tell them your name, and a second later, they've forgotten it. Annoying, right? By default, websites are just like that. Every time you refresh a page or close a tab, any information stored in JavaScript variables is wiped clean. This is because JavaScript's memory is "volatile," meaning it only lasts as long as the page is active.

✨ The Solution: Giving Websites a Memory Boost

This is where Browser Storage comes to the rescue. It's like giving the website a little notebook to jot things down. This "notebook" is part of the user's web browser and allows us to store information that persists even after the page is reloaded or the browser is closed and reopened.

The Web Storage API provides two primary mechanisms for this: localStorage and sessionStorage. Let's dive into how they work.


πŸ“¦ LocalStorage: Persistent Client-Side Data

Think of localStorage as a treasure chest πŸ΄β€β˜ οΈ that you bury in your backyard. You can put your valuables in it, and they'll stay there until you decide to dig them up, no matter how many times you go in and out of your house.

localStorage allows you to save data that persists even when the browser is closed and reopened. This makes it perfect for storing things like user preferences (e.g., theme settings), or keeping a user logged in.

Hands-On with localStorage

The localStorage object provides a few simple methods to work with. The data is stored as key-value pairs, and both the key and the value must be strings.

Storing Data: setItem()

To store a piece of information, you use the setItem() method. It takes two arguments: a key (the name of your data) and a value (the data itself).

javascript
// Let's store the user's preferred theme
localStorage.setItem('theme', 'dark');

// And their username
localStorage.setItem('username', 'CodeWizard');

Retrieving Data: getItem()

To get the data back, you use the getItem() method with the key of the data you want.

javascript
const userTheme = localStorage.getItem('theme');
const username = localStorage.getItem('username');

console.log(userTheme); // Output: 'dark'
console.log(username); // Output: 'CodeWizard'

If you try to get an item that doesn't exist, localStorage will return null.

Removing Data: removeItem()

If you want to remove a specific piece of data, you can use removeItem().

javascript
localStorage.removeItem('username');

const removedUsername = localStorage.getItem('username');
console.log(removedUsername); // Output: null

Clearing All Data: clear()

To empty the entire localStorage for your website, you can use the clear() method. Use this with caution!

javascript
localStorage.clear();

const anyRemainingData = localStorage.getItem('theme');
console.log(anyRemainingData); // Output: null

Fun Fact: localStorage has a storage limit, typically around 5-10MB per domain, which is way more than the 4KB limit of old-school cookies!


ηŸ­ζš‚ SessionStorage: Temporary Data for the Current Tab

Now, imagine you're at a library, and you get a temporary locker for your things. As long as you're in the library (your "session"), your stuff is safe in the locker. But once you leave, the locker is emptied for the next person.

That's sessionStorage in a nutshell. It stores data for the duration of a page session. A page session lasts as long as the browser is open and survives page reloads and restores. However, if you close the tab or the browser, the data is gone forever. πŸ’¨

This is incredibly useful for temporary data that shouldn't persist forever, like the contents of a shopping cart before a purchase is made or data filled in a multi-page form.

Hands-On with sessionStorage

The good news is that sessionStorage uses the exact same methods as localStorage!

javascript
// Store an item in sessionStorage
sessionStorage.setItem('cartItem', 'JavaScript for Beginners book');

// Retrieve the item
const item = sessionStorage.getItem('cartItem');
console.log(item); // Output: 'JavaScript for Beginners book'

// Remove the item
sessionStorage.removeItem('cartItem');

// Clear all sessionStorage for this domain
sessionStorage.clear();

The key difference is the lifespan of the data. Data in sessionStorage is tied to a single browser tab or window. Data in localStorage is accessible across all tabs and windows from the same origin.


πŸ“œ JSON.stringify and JSON.parse: Storing Complex Objects

So far, we've only stored simple strings. But what if you want to store something more complex, like a user's profile object?

javascript
const userProfile = {
  username: 'DataNinja',
  level: 15,
  isPro: true
};

// Let's try to store this object directly
localStorage.setItem('userProfile', userProfile);

const storedProfile = localStorage.getItem('userProfile');
console.log(storedProfile); // Output: '[object Object]'

Uh oh! 😱 That's not what we wanted. Browser storage can only handle strings. Trying to store an object directly will result in it being converted to the unhelpful string "[object Object]".

The Dynamic Duo: JSON.stringify() and JSON.parse()

To solve this, we need to convert our JavaScript object into a JSON (JavaScript Object Notation) string before storing it. And when we retrieve it, we'll need to convert it back from a JSON string to a JavaScript object.

JSON.stringify(): Object to String

This function takes a JavaScript object (or array) and converts it into a JSON string.

javascript
const userProfile = {
  username: 'DataNinja',
  level: 15,
  isPro: true
};

const userProfileString = JSON.stringify(userProfile);
console.log(userProfileString); // Output: '{"username":"DataNinja","level":15,"isPro":true}'

localStorage.setItem('userProfile', userProfileString);

Now that's a string we can work with!

JSON.parse(): String to Object

This function does the reverse. It takes a JSON string and converts it back into a JavaScript object or array.

javascript
const storedProfileString = localStorage.getItem('userProfile');

const storedProfileObject = JSON.parse(storedProfileString);

console.log(storedProfileObject); // Output: { username: 'DataNinja', level: 15, isPro: true }
console.log(storedProfileObject.username); // Output: 'DataNinja'

And just like that, we've successfully stored and retrieved a complex object! This powerful duo is essential for working with browser storage in real-world applications.

Industry Practice: Always wrap your JSON.parse() in a try...catch block. This is because if the data in localStorage is not a valid JSON string (maybe it was corrupted or not set correctly), JSON.parse() will throw an error and could crash your application.

javascript
let userProfile;
const storedProfileString = localStorage.getItem('userProfile');

try {
  userProfile = JSON.parse(storedProfileString);
} catch (error) {
  console.error("Error parsing user profile from localStorage:", error);
  // Handle the error, maybe by setting a default profile
  userProfile = { username: 'Guest', level: 1, isPro: false };
}

console.log(userProfile);

By understanding and utilizing localStorage, sessionStorage, and the JSON methods, you now have the power to create more dynamic and user-friendly web experiences that remember and react to your users' actions across sessions. Happy coding! πŸŽ‰


πŸ“š References

Challenge

Your task is to implement a robust userSettingsManager object that interacts with localStorage to persist user preferences.

You are provided with a userSettingsManager object containing four empty methods and a defaultSettings object. You must complete the implementation for each method according to the following requirements:

  1. saveSettings(settingsObject): This method must take a JavaScript object as an argument, convert it into a JSON string, and store it in localStorage using the key defined in userSettingsManager.storageKey.

  2. loadSettings(): This method must retrieve the settings string from localStorage. It needs to handle two scenarios:

    • If the data exists and is valid JSON, it should parse the string back into a JavaScript object and return it.
    • If no data is found in localStorage for the given key, or if the retrieved data is not valid JSON (causing a parsing error), it must return the defaultSettings object. Implement this with robust error handling.
  3. updateSingleSetting(key, value): This method should update a single property within the stored settings. It must first load the current settings object, update the property specified by the key with the new value, and then save the entire modified settings object back to localStorage.

  4. clearSettings(): This method must remove the user settings entry from localStorage entirely.

Expected result

Your completed code should feature a fully functional userSettingsManager object.

  • The saveSettings method should correctly serialize a JavaScript object to a JSON string using JSON.stringify() and persist it using localStorage.setItem().
  • The loadSettings method should retrieve data using localStorage.getItem(). It must contain a try...catch block to safely handle JSON.parse(). In the case of an error or if no data is found, it must return the predefined defaultSettings object.
  • The updateSingleSetting method should demonstrate the pattern of read-modify-write by calling this.loadSettings(), modifying the resulting object, and then calling this.saveSettings().
  • The clearSettings method should correctly use localStorage.removeItem() with the specified storage key to delete the entry.
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.