Level: Advanced | Player: 21_Fetch and_JSON
Learning Objectives
- Know the differences between three types of browser storage.
- You can use localStorage / sessionStorage API.
- Understand the concept and use of cookies.
- You can select the storage that suits your situation.
All examples operate in browser environment. It does not run on Node.
1. localStorage
It is permanently stored for each domain. It remains until explicitly deleted.
localStorage.setItem('username', 'Hong Gil-dong');
const name = localStorage.getItem('username');
localStorage.removeItem('username');
localStorage.clear();
The value is stored as a string only. The object is converted to JSON.stringify and saved.
2. sessionStorage
It disappears when the tab is closed. The API is the same as localStorage.
sessionStorage.setItem('cart', JSON.stringify([1, 2, 3]));
3. Cookies (overview)
- Small text automatically exchanged with the server.
- Used for authentication tokens, session identifiers, etc.
- Small capacity of 4KB. Automatic attachment to all requests → Beware of increased traffic.
- Access as
document.cookiein browser, but not recommended. It is common to set theSet-Cookieheader on the server.
4. Comparison
| Item | localStorage | sessionStorage | Cookies |
|---|---|---|---|
| Lifespan | permanent | until you close the tab | Set expiration date |
| Capacity | About 5~10MB | About 5~10MB | About 4KB |
| server transfer | X | X | automatic |
| Use | Preferences, Cache | temporary status | Certification |
Core example
| file | Contents covered |
|---|---|
| 01_localstorage.js | localStorage default |
| 02_sessionstorage.js | sessionStorage Basic |
| 03_cookie_overview.js | Example of reading cookies |
| 04_comparison.js | Comparison of three repositories |
Run each file by attaching it to <script> in the browser console or blank HTML.
⚠️ Common Mistakes
- Save the object as is → becomes the
[object Object]string. getItemmay returnnull, but it is not processed.- Store sensitive information (passwords, etc.) in localStorage.
- Misconception that sessionStorage is shared in new tabs as well.
- Handle cookies directly only as
document.cookieand ignore security options.
❓ Frequently Asked Questions (FAQ)
Q1. Is it saved in an incognito window? A. If you close the window, everything disappears.
Q2. What if the capacity is exceeded? A. QuotaExceededError occurs.
Q3. Can the domains be shared if they are different? A. No. Isolated by origin.