Middle
How can data be stored on the client in a browser? What types of storage exist and how do they differ?
sobes.tech AI
Answer from AI
In browsers, there are several main types of client-side storage:
-
Cookies
- Store small amounts of data (up to 4 KB).
- Sent to the server with each HTTP request.
- Used for sessions, authentication.
- Have an expiration date and can be protected with flags (HttpOnly, Secure).
-
LocalStorage
- Stores data as key-value pairs.
- Usually up to 5-10 MB.
- Data persists until manually deleted.
- Only available on the client side, not automatically sent to the server.
-
SessionStorage
- Similar to LocalStorage, but data only lives within a single session (tab).
- Data is deleted after the tab is closed.
-
IndexedDB
- A more complex, asynchronous storage for structured data.
- Allows storing large amounts of data.
- Supports indexes, transactions.
-
Cache Storage (Cache API)
- Used for storing HTTP request responses.
- Enables creating offline applications.
Differences:
- Cookies are sent to the server with each request, others are only on the client.
- LocalStorage and SessionStorage are simple but limited in size and data types.
- IndexedDB is suitable for complex and large data.
- SessionStorage is session-limited, LocalStorage is persistent.
Example of using LocalStorage:
localStorage.setItem('username', 'Ivan');
const user = localStorage.getItem('username');