html
/

HTML Web Storage: localStorage & sessionStorage

Last Sync: Today

On this page

10
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

html

HTML Web Storage: localStorage & sessionStorage

What is Web Storage?

Web Storage allows websites to store data in the browser. It provides two main types: localStorage and sessionStorage.

Types of Web Storage

TypeLifetimeStorage Limit
localStoragePersistent (no expiration)~5MB
sessionStorageUntil browser tab is closed~5MB

Using localStorage

JavaScriptRead-only
1
// Store data
localStorage.setItem('name', 'John');

// Get data
let name = localStorage.getItem('name');

// Remove data
localStorage.removeItem('name');

// Clear all
localStorage.clear();

Using sessionStorage

JavaScriptRead-only
1
// Store data
sessionStorage.setItem('user', 'Alice');

// Get data
let user = sessionStorage.getItem('user');

Storing Objects

JavaScriptRead-only
1
const user = { name: 'John', age: 25 };

// Store
localStorage.setItem('user', JSON.stringify(user));

// Retrieve
const storedUser = JSON.parse(localStorage.getItem('user'));

Web Storage vs Cookies

FeatureWeb StorageCookies
CapacityLarger (~5MB)Small (~4KB)
Sent to ServerNoYes
ExpirationManualAutomatic
SecurityMore secureLess secure

Use Cases

  • Store user preferences
  • Save form data temporarily
  • Cache API responses
  • Maintain session data

Best Practices

  • Do not store sensitive data
  • Use JSON for complex data
  • Clear unused data regularly
  • Handle storage limits properly
  • Use sessionStorage for temporary data

Common Mistakes

  • Storing sensitive information like passwords
  • Not converting objects to JSON
  • Ignoring storage limits
  • Overusing localStorage for large data

Conclusion

HTML Web Storage provides a simple way to store data in the browser. It improves performance and user experience when used correctly.

Try it yourself

localStorage.setItem('name', 'John');
console.log(localStorage.getItem('name'));

Test Your Knowledge

Q1
of 3

Which storage is permanent?

A
sessionStorage
B
localStorage
C
cookies
D
cache
Q2
of 3

Which storage clears on tab close?

A
localStorage
B
sessionStorage
C
cookies
D
database
Q3
of 3

How to store objects?

A
Directly
B
JSON.stringify
C
encode
D
save()

Frequently Asked Questions

What is localStorage?

It stores data permanently in the browser until manually removed.

What is sessionStorage?

It stores data temporarily until the browser tab is closed.

Is Web Storage secure?

It is safer than cookies but should not store sensitive data.

Previous

html svg

Next

html best practices

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.