Menu

Post image 1
Post image 2
1 / 2
0

localStorage vs sessionStorage vs Cookies: When to Use Each

DEV Community·Snappy Tools·about 1 month ago
#pbq5KQTI
Reading 0:00
15s threshold

Three browser storage mechanisms, each with different lifetimes, scopes, and appropriate uses. Here's when to reach for each. Overview Feature localStorage sessionStorage Cookies Capacity ~5–10 MB ~5 MB ~4 KB Expires Never (until cleared) Tab/session close Set explicitly Sent with requests No No Yes (automatically) Accessible from JS Yes Yes Yes (unless HttpOnly) Scope Domain Tab + domain Domain (configurable) localStorage Stores data with no expiry. Persists until the user clears it or the site clears it. // Write localStorage . setItem ( ' theme ' , ' dark ' ); localStorage . setItem ( ' user ' , JSON . stringify ({ id : 1 , name : ' Alice ' })); // Read const theme = localStorage . getItem ( ' theme ' ); // 'dark' const user = JSON . parse ( localStorage . getItem ( ' user ' )); // Delete localStorage . removeItem ( ' theme ' ); // Clear all localStorage . clear (); // Check existence if ( localStorage .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.

Read More