What is Web Storage - Types, Tips & Use Cases
Learn what is web storage: session, local, cookies, IndexedDB. Covers definitions, purposes, use cases, code snippets, tips, and real web development examples.
Written by RamotionOct 30, 20239 min read
Last updated: Sep 17, 2024
Web storage refers to client-side storage mechanisms that allow web apps to store data in the browser. This includes technologies like session storage, local storage, cookies, and IndexedDB.
Web storage provides essential benefits for modern web applications by enabling data to persist between browser sessions and allowing pages to store data locally without contacting a server.
Having storage available on the client side is crucial for many standard web features like shopping carts, game scores, user preferences, dynamic page content, and offline access to data.
Web storage provides much more storage capacity compared to cookies and gives web app developers control over when data expires. Overall, web storage is an essential technology for building robust web apps that can store information locally while delivering a smooth user experience.
Types of Web Storage
1. Session Storage
Session Storage allows data to be stored in the browser that will be cleared when the page session ends.
The data stored in Session Storage persists only for the duration of the browser tab or window. When the tab or window is closed, the session storage is cleared.
Some key aspects of Session Storage:
- The data is stored only for a session, meaning a browser tab.
- The data is cleared when the browser tab is closed.
- The data is isolated per origin (domain + port).
- The storage limit is larger than cookies, around 5MB.
- The data can only be accessed from the same source.
Session Storage is applicable for cases where you want to store temporary data just for a single user session, like:
- Storing a shopping cart between pages before checkout.
- Storing form data between pages in a multi-step process.
- Storing user preferences or settings for a single session.
Here is an example of using Session Storage to store form data between pages:
// Save data to sessionStorage
sessionStorage.setItem('name', 'John');
// Get saved data from sessionStorage
let name = sessionStorage.getItem('name');
Overall, Session Storage provides a way to store temporary data that will be cleared when the user closes the browser tab/window. The data is isolated per origin and tab.
2. Local Storage
Local storage is a web storage API that allows JavaScript sites and apps to store key/value data in the browser with no expiration date. The data persists even when the browser is closed and reopened.
Local storage helps store data that needs to be accessed frequently without making network requests. Unlike session storage, local storage data has no time limit. It is deleted only when explicitly told to use JavaScript, or when cleared by the browser settings.
Some common use cases for local storage include:
- Caching authentication tokens for your app's API
- Storing user preferences or settings for your app
- Saving form data so users don't lose their input if they accidentally close the tab
- Keeping track of cached data or images to improve performance
For example, you can store an object in local storage like this:
const user = {
name: 'John Doe',
age: 30,
email: '[[email protected]](mailto:[email protected])'
};
localStorage.setItem('user', JSON.stringify(user));
Later, you can retrieve it:
const user = JSON.parse(localStorage.getItem('user'));
Overall, local storage is a simple but powerful client-side storage option when you need to persist data locally in the browser. Just be mindful of the storage limits and privacy considerations when using it.
3. Cookies
Cookies are small bits of data stored in the user's browser and sent back to the server with each HTTP request. They were originally designed to enable session state and persistence on the otherwise stateless HTTP protocol.
Compared to other forms of web storage like localStorage and sessionStorage, cookies have some limitations:
- Storage space is very small, usually around 4KB.
- They are automatically sent to the server with every HTTP request, which can impact performance.
- Managing and accessing cookies through JavaScript is more cumbersome than the simple key-value APIs of localStorage and sessionStorage.
Cookies are commonly used for:
- Session management and authentication:
// Setting a cookie
document.cookie = "sessionId=38afes7a8; expires=Thu, 21 Oct 2021 07:28:00 UTC";
// Reading cookies
let cookies = document.cookie.split(';');
let sessionId = cookies.find(cookie => cookie.includes('sessionId'));
- User preferences like themes:
// Set theme
document.cookie = "theme=dark";
// Read theme
let theme = document.cookie.replace(/(?:(?:^|.*;\s*)theme\s*=\s*([^;]*).*$)|^.*$/, '$1');
- Tracking and analytics:
// Set tracking cookie
document.cookie = "trackingId=abcde12345";
While they have some use cases, cookies are limited in functionality compared to more full-featured storage like localStorage or IndexedDB. They are best suited for small data bits like session IDs or user preferences.
4. IndexedDB
IndexedDB is a low-level API for client-side storing significant amounts of structured data, including files/blobs. This API uses indexes to enable high-performance searches of this data.
While Web Storage is applicable for storing smaller amounts of data, IndexedDB is more suitable for storing large amounts of structured data.
Some common use cases for IndexedDB include:
- Storing user-generated content like forms or notes:
// Open database
const request = [indexedDB.open](http://indexeddb.open/)('notes', 1);
request.onerror = () => console.error('Database failed to open');
request.onsuccess = () => {
// Get database object
const db = request.result;
// Create object store
const objectStore = db.createObjectStore('notes', { keyPath: 'id' });
// Add data
objectStore.add({
id: 1,
title: 'My first note',
body: 'Hello world!'
});
};
- Caching large files or search indexes for performance:
// Open database
const db = await openDB('files', 1, {
upgrade(db) {
db.createObjectStore('cache');
}
});
// Add file to browser cache
const blob = await fetch('image.png').then(r => r.blob());
const tx = db.transaction('cache', 'readwrite');
tx.objectStore('cache').add(blob, 'image.png');
// Get cached file
const tx2 = db.transaction('cache');
const file = await tx2.objectStore('cache').get('image.png');
- Storing data to sync offline when network access is limited.
Web Storage Example Use Cases
Web storage allows web apps to store data locally in the browser. This opens up many use cases that are not possible with server-side storage alone. Here are some of the most common scenarios where web storage shines:
- Persisting data when offline - With web storage, web apps can save data like user preferences, shopping cart items, game state, etc., locally. This provides a good user experience even when the internet connection is lost temporarily.
- Caching server data - Frequently accessed data like user profiles can be cached client-side using web storage. This speeds up the app by avoiding extra server requests.
- Personalization - Saving user preferences and settings locally, web apps can be personalized without requiring server-side user accounts.
- Shopping carts - E-commerce sites rely on web storage to implement persistent shopping carts that survive page reloads and crashes.
- Saving game state - Web-based games use web storage to save everything from high scores to character stats and progress.
- Session management - Web storage can store session IDs and other temporary data related to the user's visit.
- Caching resources - Static resources like images, CSS, and JS files can be cached and stored locally to improve page load speed.
So, web storage opens up many possibilities like offline capability, speed improvements, personalization, and more. Any app that benefits from client-side data persistence can use the Web Storage API.
Using the Web Storage API
The Web Storage API provides mechanisms for storing data in the browser with key/value pairs. This data persists even after the browser window or tab is closed. The data is stored separately from cookies and has a larger storage capacity.
There are two main web storage objects available:
sessionStorage
- stores data only for the current session. The data is deleted when the tab or window is closed.localStorage
- stores data with no expiration date. The data persists until explicitly deleted.
The Web Storage API is relatively simple to use. Here is an example of saving data to localStorage
:
// Save data to localStorage
localStorage.setItem('myCat', 'Tom');
// Retrieve data from localStorage
const cat = localStorage.getItem('myCat');
The key things to note are:
- Data is saved as strings only. Numbers and booleans must be converted using
JSON.stringify()
. - Existing keys can be overwritten by calling
setItem()
again. - Data is scoped to the domain, so data saved from one domain cannot be accessed on another.
- The storage limit is usually 5MB per domain on modern browsers.
- The storage data persists until explicitly cleared.
Here are some tips for working with Web Storage:
- Check browser support and use feature detection. Older browsers may not support it.
- Wrap in try/catch blocks to handle exceptions gracefully.
- Use
JSON.stringify()
andJSON.parse()
for complex data types. - Prefix keys with your application name to avoid collisions.
- Call
removeItem()
andclear()
to delete data when no longer needed. - Monitor storage events
onstorage
to respond to changes across windows.
Overall, the Web Storage API provides a simple key-value pairs system for persisting data in the browser. With proper usage, it can be a valuable alternative to cookies and global variables.
Security
Web storage provides client-side storage for web applications, but security needs to be considered when using these APIs. There are a few key security best practices:
- Only store non-sensitive data. Web storage is not a secure place to store sensitive user information like passwords or financial data.
- Use HTTPS. Web storage should only be used over HTTPS connections to prevent man-in-the-middle attacks. Data stored over HTTP is visible to the network.
- Implement access controls. Use user authentication and authorization to control access to stored data. Apps should verify user identity before allowing access to stored data.
- Encrypt sensitive values. For any sensitive data that must be stored, encryption should be used to protect the data.
- Sanitize input data. User input used as keys or values should be sanitized to prevent injection attacks.
- Avoid XSS vulnerabilities. Stored data could be vulnerable to XSS if output directly to the page. Encode any output from web storage.
Through following security best practices, developers can safely leverage the benefits of web storage while mitigating risks. Being mindful of the client-side nature of web storage is critical.
Browser Support
The browser support for Web Storage APIs is generally good across modern browsers. Here are some key details:
- Session Storage and Local Storage have broad support in all primary desktop and mobile browsers, including Chrome, Firefox, Safari, Edge, and Opera.
- Cookies have near-universal support across major browsers.
- IndexedDB has good support across most modern browsers but lacks support in older browsers like IE10 and below.
To handle limited browser support, polyfills and fallbacks can be implemented:
- LocalForage provides an IndexedDB polyfill that falls back to WebSQL and LocalStorage.
- A common fallback for SessionStorage is storing data in memory on the client side.
- Cookies can be a fallback for LocalStorage when browser support is limited.
Web Storage enjoys broad support across browsers, but fallbacks should be implemented for maximum compatibility. The right polyfill brings IndexedDB support to older browsers. Cookies remain a tried and true storage mechanism with near-universal backing.
Conclusion
Web storage is helpful in many common scenarios like storing user preferences, caching data to improve performance, and persisting data when offline. The Web Storage API provides simple synchronous key-value storage through localStorage and sessionStorage objects.
When using web storage, it's essential to be mindful of browser support, security implications, and storage limits. Usage will likely grow as web apps become more complex and rely on client-side storage.
Emerging storage technologies like 3D XPoint, DNA storage, and quantum computing may shape the future of data storage broadly. However, web storage will remain essential for browser-based apps. Improved APIs like Cache Storage complement existing options. Web storage will evolve to meet the changing needs of web applications.