Local Storage
The localStorage property in JavaScript allows access to the browser's localStorage, which is a way of saving data across browser sessions. Local Storage belongs to an origin: the combination of protocol, hostname, and port.
Local Storage saves data in the current browser profile on the current device. It does not automatically sync between browsers, profiles, or devices. For example, data saved while viewing your GitHub Pages site on your laptop will not appear when you open the site on your phone. Users can also remove this data by clearing the site's stored data in their browser, so it should not be treated as a permanent backup.
NOTE
The sessionStorage property and the browser's sessionStorage are similar to localStorage except that stored data will be cleared when the page session ends.
What should you store?
Local Storage is useful for non-sensitive data such as theme preferences or a list of favourite items. Do not store passwords or secret API keys in it. JavaScript running on the same origin can read these values, and they can be inspected through the browser's developer tools. Local Storage is not a secure place to keep secrets.
Storing to localStorage
The setItem() function is used to store new data items to localStorage. The function takes two arguments, the first being the item's key and the second being the item's value. Both the key and value must be a string.
localStorage.setItem('name', 'Michael')
localStorage.setItem('title', 'Professor')
Handle saving errors
Saving to Local Storage can fail. The browser may block access to storage, or the site's storage quota may be full. Use try...catch to handle these errors and show a useful message:
try {
localStorage.setItem('name', 'Michael')
console.log('Name saved.')
} catch (error) {
console.log('Unable to save the name. Browser storage may be blocked or full.')
console.error(error)
}
The try block attempts to save the name. The success message runs only after setItem() completes without throwing an error. If accessing Local Storage or saving the value throws an error, execution moves to catch. The console shows a short message followed by the error details for debugging. Catching the error does not retry the save or make it succeed.
This example reports the result in the console. In an application, you can display the same feedback in an HTML element using textContent so the user knows whether their changes were saved.
Retrieving localStorage Items
The getItem() function is used to retrieve data items stored in localStorage. The function takes a single argument, the key of the desired item.
localStorage.getItem('name') // Michael
localStorage.getItem('title') // Professor
Deleting localStorage
Remove an assignment's data with removeItem()
Use removeItem() to reset saved data for your assignment. It takes the key of the item to remove and leaves other keys unchanged. If your assignment saves several items, call removeItem() for each key that belongs to it.
localStorage.removeItem('name')
In the earlier example, this removes 'name' while leaving 'title' unchanged. Replace 'name' with the key your assignment uses, such as 'mtm6302-a3-name'. Removing a key that does not exist has no effect. The next getItem() call for a removed key returns null.
Clear all data for the origin with clear()
The following is a separate example of clearing the entire origin's Local Storage:
localStorage.clear()
clear() removes every Local Storage key for the current origin in this browser profile, including keys used by other projects on that origin. For example, GitHub Pages projects under the same https://student.github.io origin share this storage. Use clear() only when you intend to remove all of that origin's saved data; use removeItem() for an assignment's reset feature.
Storing Objects to localStorage
The values of data items stored to localStorage must be strings. This can be quite limiting for web applications that must store and keep track of many different data items.
A workaround for this is to store an entire object or array to a data item as a string using the JSON.stringify() function. This function takes an object or an array and returns as a string. This string can then be stored to localStorage.
const string = JSON.stringify({ name: 'Michael', title: 'Professor' })
// "{"name":"Michael","title":"Professor"}"
localStorage.setItem('data', string)
When it comes to retrieving the data item, the JSON.parse() function can be used. This function parses a JSON string into a JavaScript value. In this example, it recreates an object containing the saved data.
JSON preserves data such as strings, numbers, booleans, null, arrays, and objects containing these values. It does not preserve object methods: function-valued properties are omitted by JSON.stringify(), and JSON.parse() does not restore them. Use JSON to save the data your application needs, and keep its functions in your JavaScript code.
Check for saved data
Before parsing the saved string, check whether the item exists. getItem() returns null when the key is not in localStorage, such as on a first visit or after the item has been removed.
const savedData = localStorage.getItem('data')
if (savedData !== null) {
const data = JSON.parse(savedData)
console.log(data.name)
} else {
console.log('No saved user data was found.')
}
This example uses the same 'data' key as the storing example above. If saved data exists, the code parses it and logs the user's name. Otherwise, it displays a message in the console without creating or saving a default object. This check confirms that the item exists; it does not check whether its contents are valid JSON.
Try running the storing example first, then this example to see Michael in the console. Next, run localStorage.removeItem('data') and run this example again to see the message for missing data.
Handle invalid saved JSON
A saved item can exist without containing valid JSON. For example, a string may have been saved without JSON.stringify() or edited manually in the browser's developer tools. JSON.parse() throws an error when it cannot parse the string.
Replace the previous reading example with this version. It still checks for missing data, but uses try...catch to handle a parsing error:
const savedData = localStorage.getItem('data')
if (savedData !== null) {
try {
const data = JSON.parse(savedData)
console.log('Saved user data:', data)
} catch (error) {
console.log('The saved user data could not be read as JSON.')
console.error(error)
}
} else {
console.log('No saved user data was found.')
}
The try block attempts to parse the saved string. If parsing fails, execution moves to catch, which shows a message and logs the error details in the console. The saved item remains unchanged; this code neither deletes it nor saves a default value.
This example logs the entire parsed value so we can inspect it. Valid JSON does not necessarily contain a user object with a name property; checking the expected data structure is a separate step. This try...catch handles parsing errors, not errors accessing Local Storage, because getItem() runs before the try block.
Try it
Use a separate practice key so you do not overwrite other saved data. Change the reading example's key from 'data' to 'mtm6302-json-practice', then try these steps:
- Run
localStorage.setItem('mtm6302-json-practice', JSON.stringify({ name: 'Michael' })), then run the reading example. Inspect the parsed object in the console. - Run
localStorage.setItem('mtm6302-json-practice', 'not valid JSON'), then run the reading example again. Confirm that the message and error details appear. UselocalStorage.getItem('mtm6302-json-practice')to confirm that the saved string is still there. - Run
localStorage.removeItem('mtm6302-json-practice'), then run the reading example again to see the message for missing data.
Origins and shared storage
Within the same browser profile, pages with the same origin share Local Storage. The path is not part of the origin. For example, https://student.github.io/project-one/ and https://student.github.io/project-two/ share storage because both use the origin https://student.github.io.
Changing the protocol, hostname, or port creates a different origin. For example, http://localhost:5500 and http://localhost:3000 have separate storage. Your local development site and your published GitHub Pages site also have separate storage.
Use a local development server
Run these examples through a local development server, using an address such as http://localhost:5500, instead of opening the HTML file directly. Opening a file directly uses a file: URL, for which Local Storage behaviour is undefined and can vary between browsers. Keep using the same hostname and port while testing so your page continues to access the same origin's saved data.
Choose keys for your assignment
If two projects on the same origin both save a value using the key 'name', one can overwrite the other's value. Use a descriptive key that includes your course and assignment, and use that same key when saving, reading, or removing the item:
localStorage.setItem('mtm6302-a3-name', 'Michael')
const savedName = localStorage.getItem('mtm6302-a3-name')
console.log(savedName)
localStorage.removeItem('mtm6302-a3-name')
Replace a3 with your assignment identifier. This naming convention helps avoid accidental conflicts; it does not create a separate storage area. The examples below use short keys to introduce the methods.
This YouTube video was created by Steve Griffith.