JavaScript + Node.js track

Lesson 22 · Part 6: Browser APIs

Storage

`localStorage`, `sessionStorage` and an overview of cookies

Part 6: Browser APIs2 min readFree lesson

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.cookie in browser, but not recommended. It is common to set the Set-Cookie header 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

  1. Save the object as is → becomes the [object Object] string.
  2. getItem may return null, but it is not processed.
  3. Store sensitive information (passwords, etc.) in localStorage.
  4. Misconception that sessionStorage is shared in new tabs as well.
  5. Handle cookies directly only as document.cookie and 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.

Example files

The runnable files used in this lesson. Copy them into your own project and experiment.

src/01_localstorage.jsJavaScript
/**
 *localStorage Basic — Run from browser console
 */
localStorage.setItem('username', 'Hong Gil-dong');
console.log(localStorage.getItem('username'));

const user = { id: 1, name: 'Yi Sun-sin' };
localStorage.setItem('user', JSON.stringify(user));
const restored = JSON.parse(localStorage.getItem('user'));
console.log(restored.name);

localStorage.removeItem('username');
//localStorage.clear();  // delete all
src/02_sessionstorage.jsJavaScript
/**
 *sessionStorage — disappears when tab is closed
 */
sessionStorage.setItem('step', '1');
console.log(sessionStorage.getItem('step'));

sessionStorage.setItem('cart', JSON.stringify([
  { id: 1, qty: 2 },
  { id: 5, qty: 1 },
]));

const cart = JSON.parse(sessionStorage.getItem('cart'));
console.log('Total Count:', cart.reduce((s, i) => s + i.qty, 0));
src/03_cookie_overview.jsJavaScript
/**
 *Cookies overview — document.cookie to receive all cookies as one string
 */
console.log('Current cookies:', document.cookie);

//Settings (Expires 1 day, all routes)
const oneDay = 60 * 60 * 24;
document.cookie = `lang=ko; max-age=${oneDay}; path=/`;

//Parsing example
const cookies = Object.fromEntries(
  document.cookie.split('; ').filter(Boolean).map((c) => c.split('=')),
);
console.log(cookies);
src/04_comparison.jsJavaScript
/**
 *Demo comparing three repositories
 */
localStorage.setItem('demo', 'L');
sessionStorage.setItem('demo', 'S');
document.cookie = 'demo=C; path=/';

console.log('local:', localStorage.getItem('demo'));    //permanent
console.log('session:', sessionStorage.getItem('demo')); //tab only
console.log('cookie:', document.cookie);                 //send to server

Assignment

Task 1 — Notepad

Save the information entered in <textarea> to localStorage and retain it even when refreshed.

Task 2 — Toggle dark mode

Turn dark mode on and off with a button, and save the selected state in localStorage.

  • Added dark class to <body> when in dark.
Show the reference solution

Try the assignment yourself first — comparing your attempt with a working solution is where most of the learning happens.

homework_01.htmlHTML
<!DOCTYPE html>
<html lang="ko">
  <head>
    <meta charset="UTF-8" />
<title>Notepad</title>
  </head>
  <body>
<h1>My notes</h1>
    <textarea id="memo" rows="10" cols="40"></textarea>
    <script src="homework_01.js"></script>
  </body>
</html>
homework_01.jsJavaScript
/**
 *Task 1: localStorage Notepad
 */
const KEY = 'memo:text';
const memo = document.getElementById('memo');

memo.value = localStorage.getItem(KEY) ?? '';
memo.addEventListener('input', () => {
  localStorage.setItem(KEY, memo.value);
});
homework_02.htmlHTML
<!DOCTYPE html>
<html lang="ko">
  <head>
    <meta charset="UTF-8" />
<title>Dark Mode</title>
    <style>
      body { background: #fff; color: #222; transition: 0.2s; }
      body.dark { background: #222; color: #eee; }
    </style>
  </head>
  <body>
<button id="toggle">Toggle dark mode</button>
    <script src="homework_02.js"></script>
  </body>
</html>
homework_02.jsJavaScript
/**
 *Task 2: Toggle dark mode + save to localStorage
 */
const KEY = 'theme';
const btn = document.getElementById('toggle');

if (localStorage.getItem(KEY) === 'dark') {
  document.body.classList.add('dark');
}

btn.addEventListener('click', () => {
  document.body.classList.toggle('dark');
  const mode = document.body.classList.contains('dark') ? 'dark' : 'light';
  localStorage.setItem(KEY, mode);
});

Learn this lesson with a mentor

Work through the JavaScript + Node.js track on your own, or join a guided cohort at our Pitampura campus and online.

Call NowEnroll Now