Web Storage is a modern way for web applications to store data locally within a user's browser. It is significantly better than using cookies because it is more secure, allows for much larger amounts of data (at least 5MB), and—most importantly—the data is never sent to the server with every request, which keeps your website fast.
Large Capacity: Store at least 5MB of data (cookies are limited to 4KB).
Security: Data stays in the browser and isn't exposed in HTTP headers.
Origin-Based:Data is tied to your specific domain and protocol.
Performance:Local storage doesn't slow down server requests.
The Web Storage API provides two distinct ways to save data, depending on how long you want that data to last.
Before using web storage, always check if the user's browser supports the API to prevent errors.
The localStorage object keeps data even after the browser is closed and reopened.
Code Example: Storing and Retrieving Preferences
Note:Data is always stored as strings. If you want to store numbers or objects, you must convert them (e.g., using Number() or JSON.stringify()).
This example uses localStorage to remember how many times a user clicked a button, even if they return days later.
Use sessionStorage for data that should only last as long as the current tab is open. The syntax is exactly the same as localStorage.
Session Counter Example:
Capacity:Use Web Storage for data larger than 4KB.
Duration:localStorage for permanent data and sessionStorage for temporary data.
Formatting:Remember that everything is stored as a string!