Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Web Storage – localStorage & sessionSto | HTML Course lesson | BraveProgrammer
  1. Courses
  2. /
  3. HTML Course

Lesson 32 of 55

·HTML

Web Storage – localStorage & sessionStorage

9 min

Course progress58%

What you'll learn

Keep these ideas in mind as you work through the lesson.

5 points
  • Web Storage API methods (`setItem`, `getItem`, `removeItem`, `clear`)
  • Differences between `localStorage` (persistent) and `sessionStorage` (tab‑scoped)
  • Same‑origin policy and storage size limits (~5 MB)
  • Storing structured data with JSON serialization
  • Cross‑tab synchronization using the `storage` event

Storing Data on the Client

Both APIs provide a simple key‑value store (strings only).

// Save a value
localStorage.setItem('theme', 'dark');
// Retrieve
const theme = localStorage.getItem('theme');

// Session‑only data
sessionStorage.setItem('temp', '123');

Differences

  • localStorage – Persists across sessions until cleared; shared across all tabs/windows of the same origin.
  • sessionStorage – Clears when the tab/window closes; scoped to a single browsing context.

Usage tips

  • Use JSON for structured data: localStorage.setItem('profile', JSON.stringify(obj));.
  • Listen to the storage event to sync changes across tabs:
window.addEventListener('storage', e => {
  if (e.key === 'theme') { applyTheme(e.newValue); }
});
  • Respect storage limits (~5 MB) and never store sensitive data in plain text.
  • When storing large objects, consider compression (e.g., LZString) before saving.

Quick checklist for Web Storage

  1. Data stored as strings (use JSON.stringify for objects)? ✅
  2. Sensitive info avoided (no passwords, tokens)? ✅
  3. storage event used for cross‑tab sync where needed? ✅
  4. Storage size monitored (avoid exceeding ~5 MB)? ✅
  5. Fallback strategy for browsers without Storage (e.g., cookies) implemented? ✅

Tip: Use localStorage for UI preferences (theme, language) and sessionStorage for temporary form state that shouldn’t survive a page reload.

Make it stickPractice what you've learned1 quiz · 2 practical tests · Optional activities from HTML CourseBrowse activities
Previous lessonHTML5 Drag-and-Drop APIContinue to lesson 33IndexedDB – Browser‑Side Structured DataBack to HTML Course curriculum