Just a few weeks until the 2021 JavaScript Full-Stack Bootcamp opens.
Signup to the waiting list!
Introduction
The Web Storage API defines two storage mechanisms which are very important: Session Storage and Local Storage.
They are part of the set of storage options available on the Web Platform, which includes:
Application Cache is deprecated, and Web SQL is not implemented in Firefox, Edge and IE.
Both Session Storage and Local Storage provide a private area for your data. Any data you store cannot be accessed by other websites.
Session Storage maintains the data stored into it for the duration of the page session. If multiple windows or tabs visit the same site, they will have two different Session Storage instances.
When a tab/window is closed, the Session Storage for that particular tab/window is cleared.
Session storage is meant to allow the scenario of handling different processes happening on the same site independently, something not possible with cookies for example, which are shared in all sessions.
Local Storage instead persists the data until it’s explicitly removed, either by you or by the user. It’s never cleaned up automatically, and it’s shared in all the sessions that access a site.
Both Local Storage and Session Storage are protocol specific: data stored when the page is accessed using http
is not available when the page is served with https
, and vice versa.
Web Storage is only accessible in the browser. It’s not sent to the server like cookies do.
How to access the storage
Both Local and Session Storage are available on the window
object, so you can access them using sessionStorage
and localStorage
.
Their set of properties and methods is exactly the same, because they return the same object, a Storage object.
The Storage Object has a single property, length
, which is the number of data items stored into it.
Methods
setItem(key, value)
setItem()
adds an item to the storage. Accepts a string as key, and a string as a value:
localStorage.setItem('username', 'flaviocopes')
localStorage.setItem('id', '123')
If you pass any value that’s not a string, it will be converted to string:
localStorage.setItem('test', 123) //stored as the '123' string
localStorage.setItem('test', { test: 1 }) //stored as "[object Object]"
getItem(key)
getItem()
is the way to retrieve a string value from the storage, by using the key string that was used to store it:
localStorage.getItem('username') // 'flaviocopes'
localStorage.getItem('id') // '123'
removeItem(key)
removeItem()
removes the item identified by key
from the storage, returning nothing (an undefined
value):
localStorage.removeItem('id')
key(n)
Every item you store has an index number.
It might appear the number is consecutive, so the first time you use
setItem()
, that item can be referenced usingkey(0)
, the next withkey(1)
and so on, but it’s not. MDN says “The order of keys is user-agent defined, so you should not rely on it”.
If you reference a number that does not point to a storage item, it returns null
.
clear()
clear()
removes everything from the storage object you are manipulating:
localStorage.setItem('a', 'a')
localStorage.setItem('b', 'b')
localStorage.length //2
localStorage.clear()
localStorage.length //0
Storage size limits
Through the Storage API you can store a lot more data than you would be able with cookies.
The amount of storage available on Web might differ by storage type (local or session), browser, and by device type. A research by html5rocks.com points out those limits:
Desktop
- Chrome, IE, Firefox: 10MB
- Safari: 5MB for local storage, unlimited session storage
Mobile
- Chrome, Firefox: 10MB
- iOS Safari and WebView: 5MB for local storage, session storage unlimited unless in iOS6 and iOS7 where it’s 5MB
- Android Browser: 2MB local storage, unlimited session storage
Going over quota
You need to handle quota errors, especially if you store lots of data. You can do so with a try/catch:
try {
localStorage.setItem('key', 'value')
} catch (domException) {
if (
['QuotaExceededError', 'NS_ERROR_DOM_QUOTA_REACHED'].includes(
domException.name
)
) {
// handle quota limit exceeded error
}
}
Developer Tools
The DevTools of the major browsers all offer a nice interface to inspect and manipulate the data stored in the Local and Session Storage.
Chrome
Firefox
Safari
Download my free JavaScript Beginner's Handbook
The 2021 JavaScript Full-Stack Bootcamp will start at the end of March 2021. Don't miss this opportunity, signup to the waiting list!
More browser tutorials:
- Some useful tricks available in HTML5
- How I made a CMS-based website work offline
- The Complete Guide to Progressive Web Apps
- The Fetch API
- The Push API Guide
- The Channel Messaging API
- Service Workers Tutorial
- The Cache API Guide
- The Notification API Guide
- Dive into IndexedDB
- The Selectors API: querySelector and querySelectorAll
- Efficiently load JavaScript with defer and async
- The Document Object Model (DOM)
- The Web Storage API: local storage and session storage
- Learn how HTTP Cookies work
- The History API
- The WebP Image Format
- XMLHttpRequest (XHR)
- An in-depth SVG tutorial
- What are Data URLs
- Roadmap to learn the Web Platform
- CORS, Cross-Origin Resource Sharing
- Web Workers
- The requestAnimationFrame() guide
- What is the Doctype
- Working with the DevTools Console and the Console API
- The Speech Synthesis API
- How to wait for the DOM ready event in plain JavaScript
- How to add a class to a DOM element
- How to loop over DOM elements from querySelectorAll
- How to remove a class from a DOM element
- How to check if a DOM element has a class
- How to change a DOM node value
- How to add a click event to a list of DOM elements returned from querySelectorAll
- WebRTC, the Real Time Web API
- How to get the scroll position of an element in JavaScript
- How to replace a DOM element
- How to only accept images in an input file field
- Why use a preview version of a browser?
- The Blob Object
- The File Object
- The FileReader Object
- The FileList Object
- ArrayBuffer
- ArrayBufferView
- The URL Object
- Typed Arrays
- The DataView Object
- The BroadcastChannel API
- The Streams API
- The FormData Object
- The Navigator Object
- How to use the Geolocation API
- How to use getUserMedia()
- How to use the Drag and Drop API
- How to work with scrolling on Web Pages
- Handling forms in JavaScript
- Keyboard events
- Mouse events
- Touch events
- How to remove all children from a DOM element
- How to create an HTML attribute using vanilla Javascript
- How to check if a checkbox is checked using JavaScript?
- How to copy to the clipboard using JavaScript
- How to disable a button using JavaScript
- How to make a page editable in the browser
- How to get query string values in JavaScript with URLSearchParams
- How to remove all CSS from a page at once
- How to use insertAdjacentHTML
- Safari, warn before quitting
- How to add an image to the DOM using JavaScript
- How to reset a form
- How to use Google Fonts