Kindle upvote it, it will motivate me to create this type of articles for you πΌ
What are the key differences between localStorage and sessionStorage?
Both localStorage
and sessionStorage
are part of the Web Storage API and are used to store key-value pairs in the browser. However, they have key differences:
Feature | localStorage | sessionStorage |
Persistence | Data persists even after the browser is closed and reopened. | Data is cleared when the page session ends (i.e., when the browser/tab is closed). |
Scope | Data is shared across all tabs and windows of the same origin. | Data is limited to the specific tab in which it was stored. |
Expiration | No expiration; remains until manually cleared. | Cleared when the session ends. |
Storage Limit | ~5MB per origin (varies by browser). | ~5MB per origin (varies by browser). |
Accessibility | Available across multiple tabs, windows, and browser sessions. | Available only in the same tab during its session. |
When to Use:
Use
localStorage
when you need to persist data across sessions, such as user preferences, theme settings, or authentication tokens.Use
sessionStorage
when you need temporary storage for a single session, like form inputs or one-time state management that shouldnβt persist beyond the session.
What is the difference between localStorage, sessionStorage, session and cookies?
The key differences between localStorage
, sessionStorage
, session
, and cookies
are based on their scope, persistence, size limits, and accessibility. Here's a detailed comparison:
Feature | localStorage | sessionStorage | session | cookies |
Persistence | Data persists even after the browser is closed. | Data is cleared when the tab/browser session ends. | Data exists until the user logs out or the session times out. | Can have an expiration date or session-based persistence. |
Scope | Shared across all tabs and windows of the same origin. | Only available in the same tab/window. | Available across all tabs of the same site during a session. | Shared across multiple tabs and sent with every HTTP request. |
Size Limit | ~5MB per origin. | ~5MB per origin. | Server-defined, usually smaller than local/session storage. | ~4KB per cookie. |
Accessibility | Accessible via JavaScript (window.localStorage ). | Accessible via JavaScript (window.sessionStorage ). | Accessible via the server and sometimes via JavaScript. | Accessible via JavaScript (if not HttpOnly ) and automatically sent with HTTP requests. |
Security | Not sent with HTTP requests; vulnerable to XSS attacks. | Not sent with HTTP requests; vulnerable to XSS attacks. | More secure as it exists on the server side. | Can be secure (HttpOnly , Secure , SameSite attributes), but still vulnerable to CSRF. |
Use Cases | Storing persistent data like user preferences, authentication tokens. | Temporary data like form inputs, filters, or state management per tab. | Server-side authentication, tracking logged-in users. | Authentication, user tracking, storing small bits of user data. |
When to Use:
localStorage
β Persistent data (e.g., user settings, themes).sessionStorage
β Temporary session-based data (e.g., unsaved form data).session
β Server-side user authentication (e.g., login sessions).cookies
β Authentication, tracking, and storing small data that needs to be sent with requests.
How much data can be stored in localStorage/sessionStorage, and how is storage allocated?
Storage Limits in localStorage
and sessionStorage
Both localStorage
and sessionStorage
have a typical storage limit of 5MB per origin (domain + protocol + port). However, this limit is not strictly defined and can vary based on the browser.
Storage Allocation Details
Per Origin Basis: Storage is allocated per origin (same domain, protocol, and port).
Shared Between
localStorage
andsessionStorage
: They share the 5MB quota but store data separately.UTF-16 Encoding: Storage is measured in characters, and most browsers store strings as UTF-16, meaning each character takes 2 bytes.
Browsers May Vary: Some browsers allocate more than 5MB, and storage can be affected by system storage availability.
Browser Storage Limits (Approximate)
Browser | localStorage Limit | sessionStorage Limit |
Chrome | 10MB | 10MB |
Firefox | 10MB | 10MB |
Edge | 10MB | 10MB |
Safari | 5MB | 5MB |
Opera | 10MB | 10MB |
IE (legacy) | 5MB | 5MB |
Checking Available Storage in JavaScript
You can check how much storage is available using a function like this:
function getAvailableStorage() {
let data = '1';
try {
while (true) {
localStorage.setItem('test', data);
data += data; // Exponentially increase the stored data
}
} catch (e) {
console.log(`Approximate localStorage limit reached: ${data.length * 2 / 1024} KB`);
localStorage.removeItem('test'); // Clean up
}
}
getAvailableStorage();
UTF-16
Understanding UTF-16 in Local Storage
localStorage
and sessionStorage
store data as strings using UTF-16 encoding. This affects storage size calculations because each character in UTF-16 typically takes 2 bytes.
UTF-16 Basics
UTF-16 is a character encoding format that uses:
2 bytes (16 bits) for most characters (e.g., ASCII characters, Latin letters).
4 bytes for surrogate pairs (e.g., emojis, some non-Latin scripts like certain Chinese characters).
This means that storing a simple ASCII string takes 2 bytes per character, while some special characters (like emojis) take 4 bytes.
Impact on Local Storage Size
Since browsers allocate 5MB (β 5,242,880 bytes) per origin, this translates to:
β 2.5 million ASCII characters (
5MB / 2 bytes per character
).β 1.3 million emoji characters (
5MB / 4 bytes per character
).
Example: UTF-16 Storage Size Calculation
Let's store some data in localStorage
and check how many bytes it takes:
function getByteSize(str) {
return new Blob([str]).size; // Returns the byte size of the string
}
let text = "A"; // Simple ASCII character
console.log(getByteSize(text)); // Output: 2 bytes (UTF-16)
let emoji = "π"; // Emoji (surrogate pair)
console.log(getByteSize(emoji)); // Output: 4 bytes (UTF-16)
Practical Considerations
Storage Limits Depend on Encoding
- Since
localStorage
andsessionStorage
use UTF-16, the actual amount of stored characters varies.
- Since
Minimizing Storage Usage
Convert objects to JSON (
JSON.stringify()
) instead of using plain strings.Use compression techniques (e.g., LZ compression or Base64 encoding).
Avoiding Errors
- If you exceed the quota, browsers will throw a
QuotaExceededError
when usingsetItem()
.
- If you exceed the quota, browsers will throw a
Does localStorage persist after closing the browser? How does sessionStorage behave across tabs?
1. Does localStorage
persist after closing the browser?
Yes, localStorage
persists even after closing and reopening the browser. The data remains stored indefinitely until it is manually removed by:
Calling
localStorage.removeItem(key)
orlocalStorage.clear()
.Clearing browser storage manually in DevTools.
The user clearing site data or cookies from browser settings.
Example: Persisting Data in localStorage
javascriptCopyEdit// Store data
localStorage.setItem("username", "Ravi");
// Retrieve data even after browser restarts
console.log(localStorage.getItem("username")); // Output: "Ravi"
2. How does sessionStorage
behave across tabs?
sessionStorage
is tab-specific, meaning:
It is only available in the tab where it was set.
If you open a new tab or window,
sessionStorage
does not carry over.If you refresh the page,
sessionStorage
persists.If you close the tab or browser window, the data is lost.
Example: Session Storage Scope
javascriptCopyEdit// Store data in sessionStorage
sessionStorage.setItem("theme", "dark");
// Retrieve data within the same tab
console.log(sessionStorage.getItem("theme")); // Output: "dark"
// Open a new tab (same site) -> sessionStorage will be empty
console.log(sessionStorage.getItem("theme")); // Output: null
Key Differences in Persistence
Feature | localStorage | sessionStorage |
Persists after closing browser? | β Yes | β No |
Shared across tabs/windows? | β Yes (same origin) | β No (tab-specific) |
Persists after page reload? | β Yes | β Yes |
Cleared manually? | β Yes (via JS or DevTools) | β Yes (closing tab/browser) |
What happens when the storage limit is exceeded?
What Happens When the Storage Limit is Exceeded in localStorage
or sessionStorage
?
When you try to store more data than the browser's allocated limit (usually 5MB per origin), the browser throws a QuotaExceededError
and prevents adding new data.
Behavior When Exceeding the Limit
Existing data remains intact β The storage won't delete previous data.
New data won't be added β The
setItem()
operation fails.Error handling is needed β If not handled, it can crash scripts.
Example: Handling QuotaExceededError
You can catch this error using a try...catch
block:
try {
let bigData = "x".repeat(1024 * 1024 * 5); // Try storing ~5MB of data
localStorage.setItem("test", bigData);
} catch (e) {
if (e instanceof DOMException && e.name === "QuotaExceededError") {
console.error("Storage limit exceeded! Consider clearing some space.");
}
}
How to Avoid Exceeding Storage Limits
Use Compression β Store data in compressed formats (e.g., Base64, LZ compression).
Store Only Necessary Data β Avoid storing large JSON objects directly.
Use IndexedDB for Large Data β It provides a more scalable solution for large datasets.
Regularly Clear Unused Data β Remove old entries using
localStorage.removeItem()
.
What are the risks of using localStorage for sensitive data like tokens, and how can you secure it?
Risks of Using localStorage
for Sensitive Data Like Tokens
Storing sensitive data like authentication tokens in localStorage
is generally not recommended due to security risks:
π Vulnerable to XSS (Cross-Site Scripting) Attacks
If an attacker injects malicious JavaScript into your website, they can steal tokens stored in
localStorage
usinglocalStorage.getItem("token")
.Example XSS attack:
console.log(localStorage.getItem("authToken")); // Malicious script can access this
π« No Secure or HttpOnly Flags
- Unlike cookies,
localStorage
cannot be marked asHttpOnly
orSecure
, making it accessible via JavaScript.
- Unlike cookies,
π‘ Tokens Are Not Automatically Sent with Requests
- Unlike cookies,
localStorage
tokens need to be manually added to headers (Authorization: Bearer <token>
), increasing the risk of improper handling.
- Unlike cookies,
π No Automatic Expiry
- Data in
localStorage
persists indefinitely unless manually removed, increasing the attack window if a user's device is compromised.
- Data in
How to Secure Tokens in Frontend Applications?
Instead of localStorage
, consider these approaches:
β 1. Use HTTP-Only Secure Cookies (Best Practice)
Store tokens in secure, HttpOnly cookies that are automatically sent with each request.
Example server-side setup:
res.cookie("authToken", token, { httpOnly: true, // Prevents JavaScript access secure: true, // Only sent over HTTPS sameSite: "Strict", // Prevents CSRF maxAge: 86400000, // 1-day expiry });
Pros: Protects against XSS since JavaScript cannot access
HttpOnly
cookies.
β
2. Use sessionStorage
for Short-Lived Tokens
If you must store a token on the client side, use
sessionStorage
so it's cleared when the tab is closed.Example:
sessionStorage.setItem("authToken", token);
Cons: Still vulnerable to XSS.
β 3. Implement Token Rotation (Short-Lived Access Token + Refresh Token)
Store short-lived access tokens in memory (
useState
in React) and refresh tokens in secure HTTP-only cookies.Flow:
Request access token via API.
Store access token in memory.
When expired, use the refresh token (stored in a secure cookie) to get a new one.
What If You Still Need to Use localStorage
?
β οΈ Not recommended, but if unavoidable:
Encrypt the token before storing it using AES encryption.
import CryptoJS from "crypto-js"; const encryptedToken = CryptoJS.AES.encrypt(token, "secret-key").toString(); localStorage.setItem("authToken", encryptedToken);
Always validate tokens on the server before trusting them.
Set up CSP (Content Security Policy) to block inline scripts and limit XSS risks.
Final Recommendation
πΉ Best choice: Store tokens in secure, HttpOnly cookies.
πΉ If session-based: Use sessionStorage
instead of localStorage
.
πΉ Avoid storing long-lived sensitive data in localStorage
due to XSS risks.
How does localStorage handle cross-domain security?
How Does localStorage
Handle Cross-Domain Security?
π Same-Origin Policy (SOP) Enforcement
localStorage
follows the Same-Origin Policy (SOP), meaning:
Data stored in
localStorage
is only accessible from the same origin (protocol + domain + port).Different domains, subdomains, or protocols cannot access each otherβs
localStorage
data.
β What Defines the "Same Origin"?
Two URLs have the same origin if they have the same:
Protocol (HTTP vs. HTTPS)
Domain (e.g.,
example.com
vs.api.example.com
β Different origins)Port (if specified, e.g.,
http://localhost:3000
βhttp://localhost:5000
)
Origin 1 | Origin 2 | Access to localStorage ? |
https://example.com | https://example.com | β Yes (Same origin) |
https://example.com | https://sub.example.com | β No (Different subdomain) |
https://example.com | http://example.com | β No (Different protocol) |
http://localhost:3000 | http://localhost:5000 | β No (Different port) |
π Can localStorage
Be Shared Across Domains?
By default, NO β localStorage
is completely isolated per origin.
However, there are some indirect ways to share data across domains:
π 1. Using postMessage
for Cross-Origin Communication
If two domains need to communicate, they can use
window.postMessage()
.Example: Parent window (example.com) and an iframe (sub.example.com).
π¨βπ» Example: Sending localStorage
data across domains
// In parent window (example.com)
const iframe = document.getElementById("myIframe");
iframe.contentWindow.postMessage(localStorage.getItem("token"), "https://sub.example.com");
// In iframe (sub.example.com)
window.addEventListener("message", (event) => {
if (event.origin !== "https://example.com") return;
console.log("Received token:", event.data);
});
π 2. Using a Backend API for Shared Storage
Store the data in a backend database, then fetch it via API from multiple domains.
More secure than
localStorage
.
π 3. Setting a Shared Cookie Instead
- Cookies with
SameSite=None; Secure
can be shared across domains if both use HTTPS.
π Security Risks & Considerations
Cross-Site Scripting (XSS): Attackers can inject scripts to steal
localStorage
data.Session Hijacking: Since
localStorage
data never expires, stolen tokens can be used indefinitely.Mitigation Strategies:
Use HTTP-only Secure Cookies instead of
localStorage
for sensitive data.Implement CSP (Content Security Policy) to prevent XSS attacks.
π Summary
Feature | localStorage Behavior |
Same-Origin Policy | β Yes, enforced |
Cross-domain access | β No, blocked by browser |
Sharing data across domains? | π Possible via postMessage or API |
Security concerns | π¨ XSS risks, no automatic expiration |
How can you add, retrieve, remove, and clear items in localStorage/sessionStorage?
How to Add, Retrieve, Remove, and Clear Items in localStorage
and sessionStorage
Both localStorage
and sessionStorage
provide simple methods for storing and managing key-value pairs in the browser.
1οΈβ£ Adding (Storing) Items
You can store data using setItem(key, value)
.
β οΈ Values must be strings. If storing objects, convert them to JSON using
JSON.stringify()
.
Example: Storing Data
// Using localStorage
localStorage.setItem("username", "Ravi");
// Using sessionStorage
sessionStorage.setItem("sessionID", "12345");
Storing Objects in Storage
const user = { name: "Ravi", age: 24 };
// Convert to JSON before storing
localStorage.setItem("user", JSON.stringify(user));
2οΈβ£ Retrieving Items
To get stored data, use getItem(key)
.
If the key doesnβt exist, it returns
null
.
Example: Retrieving Data
// Get data from localStorage
console.log(localStorage.getItem("username")); // Output: Ravi
// Get data from sessionStorage
console.log(sessionStorage.getItem("sessionID")); // Output: 12345
Retrieving Objects
const storedUser = JSON.parse(localStorage.getItem("user"));
console.log(storedUser.name); // Output: Ravi
3οΈβ£ Removing a Specific Item
To delete a specific key, use removeItem(key)
.
Example: Removing Data
localStorage.removeItem("username");
sessionStorage.removeItem("sessionID");
4οΈβ£ Clearing All Storage
To remove all stored data from localStorage
or sessionStorage
, use clear()
.
Example: Clearing Storage
localStorage.clear(); // Removes all keys from localStorage
sessionStorage.clear(); // Removes all keys from sessionStorage
π Summary
Operation | localStorage Example | sessionStorage Example |
Store | localStorage.setItem("key", "value") | sessionStorage.setItem("key", "value") |
Retrieve | localStorage.getItem("key") | sessionStorage.getItem("key") |
Remove Specific Item | localStorage.removeItem("key") | sessionStorage.removeItem("key") |
Clear All Data | localStorage.clear() | sessionStorage.clear() |
Can localStorage trigger events? How is the storage event used for syncing data across tabs?
Can localStorage
Trigger Events?
Yes! localStorage
can trigger the storage
event when changes occur in another tab (but not in the same tab).
π How Does the storage
Event Work?
The
storage
event fires only whenlocalStorage
is modified in a different tab or window of the same origin.It does not trigger in the same tab where the change occurs.
It helps in syncing data across multiple open tabs of a website.
π Example: Syncing Data Across Tabs
Imagine a user logs in on one tab, and you want other open tabs to update automatically.
π¨βπ» Step 1: Add an Event Listener for Storage Changes
In all tabs, listen for changes using window.addEventListener("storage", callback)
.
window.addEventListener("storage", (event) => {
console.log("Storage event detected:", event);
if (event.key === "authToken") {
console.log("New authToken:", event.newValue);
if (!event.newValue) {
console.log("User logged out in another tab.");
// Redirect to login page
window.location.href = "/login";
}
}
});
π₯οΈ Step 2: Modify localStorage
in One Tab
When a user logs in, store the token:
localStorage.setItem("authToken", "abc123");
Now, all other open tabs detect this change and update accordingly.
π Storage Event Properties
When the storage
event fires, it provides:
Property | Description |
key | The key that changed ("authToken" ) |
oldValue | Previous value before the change |
newValue | Updated value after the change |
url | The URL of the page where the change happened |
storageArea | Always localStorage (since sessionStorage doesn't trigger this event) |
Example event log:
{
"key": "authToken",
"oldValue": "xyz789",
"newValue": "abc123",
"url": "https://example.com",
"storageArea": localStorage
}
π― Practical Use Cases
β 1. Auto Logout Across Tabs
- If a user logs out in one tab (
localStorage.removeItem("authToken")
), other tabs detect the change and log out the user.
β 2. Theme Syncing
- If a user switches to dark mode in one tab, update it in all tabs:
localStorage.setItem("theme", "dark");
β 3. Real-Time Data Sync
- Update notifications, cart items, or app settings in real time.
β οΈ Limitations & Considerations
Doesn't Work in the Same Tab
storage
event only fires in other tabs, not the one making the change.
Not for
sessionStorage
sessionStorage
does not trigger storage events.
No Initial Load Event
- The event only fires on changes, not when a page first loads.
π Final Takeaway
β
localStorage
can trigger a storage
event across tabs for syncing data.
β
Use window.addEventListener("storage", callback)
to detect changes.
β
Helps in auto logout, theme syncing, real-time updates, and more.
How do cookies differ from localStorage and sessionStorage?
π Cookies vs. localStorage
vs. sessionStorage
All three methodsβcookies, localStorage
, and sessionStorage
βare used for storing data in the browser, but they have significant differences in terms of lifetime, storage capacity, accessibility, and security.
π Quick Comparison Table
Feature | Cookies πͺ | localStorage π¦ | sessionStorage π |
Max Size | ~4KB per cookie | ~5-10MB | ~5-10MB |
Expiration | Set manually (expires or max-age ) | Never expires (persists after closing browser) | Expires when tab is closed |
Scope | Accessible across tabs, windows, and server | Accessible in same origin, across tabs | Accessible only in the same tab |
Access | Sent with every request to the server | Only accessible via JavaScript | Only accessible via JavaScript |
Security | Vulnerable to XSS, CSRF if not secured properly | Vulnerable to XSS | Vulnerable to XSS |
Use Case | Authentication (HTTP-only, Secure cookies) | Storing user preferences, tokens (not recommended) | Temporary session-based data |
π Detailed Differences
1οΈβ£ Size Limit
Cookies: Limited to ~4KB total per domain.
localStorage & sessionStorage: 5-10MB, much larger.
2οΈβ£ Data Expiration
Cookies: Can be set to expire at a specific time (e.g.,
max-age=3600
for 1 hour).localStorage: Persists forever until manually removed.
sessionStorage: Expires when the tab is closed.
3οΈβ£ Accessibility & Scope
Cookies: Available to both client (JavaScript) and server (sent with HTTP requests).
localStorage: Only accessible on the client-side.
sessionStorage: Same as
localStorage
, but only for the current tab.
4οΈβ£ Security Risks
Attack Type | Cookies | localStorage | sessionStorage |
XSS (Cross-Site Scripting) | β Yes (unless HttpOnly ) | β Yes (fully exposed) | β Yes (fully exposed) |
CSRF (Cross-Site Request Forgery) | β Yes (sent with requests) | β No | β No |
Cookies are automatically sent with requests, making them vulnerable to CSRF attacks.
localStorage and sessionStorage are exposed to XSS attacks if malicious scripts run on the page.
5οΈβ£ Best Use Cases
Use Case | Recommended Storage |
Authentication (tokens, sessions) | β Cookies (HTTP-Only, Secure) |
User preferences (theme, language, UI settings) | β
localStorage |
Temporary data (form drafts, navigation state) | β
sessionStorage |
Shopping carts (without login) | β
localStorage |
Cross-tab communication | β
localStorage |
π When NOT to Use localStorage
β For storing authentication tokens β Use secure HTTP-only cookies instead.
β For sensitive data (passwords, API keys, user info) β Vulnerable to XSS attacks.
π Summary
Scenario | Use localStorage ? | Use sessionStorage ? | Use Cookies? |
Storing login tokens | β No | β No | β Yes (Secure, HTTP-only) |
Remembering theme settings | β Yes | β No | β No |
Saving form progress (temporary) | β No | β Yes | β No |
Storing CSRF tokens | β No | β No | β Yes |
Shopping cart (without login) | β Yes | β No | β No |
What are the performance implications of using localStorage for high-frequency operations?
π Performance Implications of Using localStorage
for High-Frequency Operations
Using localStorage
for frequently accessed or updated data can hurt performance due to its synchronous blocking nature, lack of indexing, and slower read/write speeds. Hereβs why:
β³ 1. Synchronous, Blocking I/O
Every
localStorage.getItem()
andlocalStorage.setItem()
call blocks the main thread until it completes.If called frequently (e.g., every user action or animation frame), it freezes the UI, causing jank.
Example of bad usage in an animation loop:
function updateScore(score) { localStorage.setItem("score", score); // π¨ Freezes the main thread } requestAnimationFrame(updateScore);
β
Better Approach: Store in memory (state
, Map
, or IndexedDB
) and sync less frequently.
π’ 2. Slower Read/Write Speeds Compared to Memory
localStorage
operations are much slower than reading from JavaScript variables (RAM).Reason: Every read/write operation requires serializing and deserializing strings, which adds overhead.
β³ Performance Test (Using console.time()
)
console.time("localStorage Write");
localStorage.setItem("key", JSON.stringify({ name: "Ravi", age: 24 }));
console.timeEnd("localStorage Write"); // β οΈ ~1-5ms
console.time("Memory Write");
const data = { name: "Ravi", age: 24 };
console.timeEnd("Memory Write"); // β
~0.001ms
π‘ Memory (JS objects/variables) is ~1000x faster than localStorage
!
π¦ 3. Lack of Efficient Indexing
localStorage
is a key-value store without indexing.Unlike IndexedDB or databases, it does not support fast queries.
Searching data requires looping through all keys:
for (let i = 0; i < localStorage.length; i++) { console.log(localStorage.key(i), localStorage.getItem(localStorage.key(i))); }
- Bad for large datasets (e.g., storing thousands of user transactions).
β Alternative: Use IndexedDB for structured, indexed storage.
πΎ 4. Storage Limits & Performance Degradation
Most browsers limit
localStorage
to 5MB-10MB per origin.Exceeding this limit throws an error:
try { localStorage.setItem("bigData", "x".repeat(5 * 1024 * 1024)); // ~5MB } catch (e) { console.error("Storage limit exceeded!", e); }
If the storage is nearly full, writes become even slower.
β
Solution: Use sessionStorage
(for short-lived data) or IndexedDB (for large data).
π 5. No Automatic Cross-Tab Sync
localStorage
does not sync automatically between tabs.The only way to sync is through the
storage
event, but it fires only when another tab modifies storage.
β Better for syncing? Use WebSockets or BroadcastChannel API for real-time updates.
π When Should You NOT Use localStorage
?
Use Case | Good for localStorage ? | Better Alternative |
User Preferences (Theme, Language) | β Yes | β
localStorage |
Authentication Tokens (Security Risk!) | β No | β HTTP-only Cookies |
Frequent Reads/Writes (e.g., Chat, Live Updates) | β No | β IndexedDB, WebSockets |
Large Data (Images, JSON, User Activity Logs) | β No | β IndexedDB, Cache API |
Cross-Tab Communication | β No | β BroadcastChannel API |
β Best Practices for Performance
1οΈβ£ Use localStorage
only for small, infrequent data (e.g., user preferences, cache).
2οΈβ£ Avoid using it inside loops or real-time updatesβuse memory (variables) instead.
3οΈβ£ Batch updates instead of frequent writes (e.g., debounce saves).
4οΈβ£ Use IndexedDB for large or structured data (e.g., user transactions, offline storage).
5οΈβ£ Consider using WebSockets or BroadcastChannel for real-time syncing across tabs.
Would you like a real-world example of optimizing localStorage
for a React app? π
How would you implement a wrapper for localStorage to simplify JSON handling?
π Creating a localStorage
Wrapper for Simplified JSON Handling
Since localStorage
only stores strings, we often need to serialize (JSON.stringify
) and deserialize (JSON.parse
) manually.
A wrapper can simplify this process while handling errors, expiration, and default values.
π Features of the Wrapper
β
Automatic JSON parsing & stringifying
β
Handles errors gracefully (try/catch)
β
Supports default values if key is missing
β
Optional expiration time support
β
Easy to use with simple API methods
π Implementation
class StorageHelper {
constructor(storageType = "localStorage") {
this.storage = storageType === "sessionStorage" ? sessionStorage : localStorage;
}
// β
Set item with optional expiration time (in minutes)
setItem(key, value, expiryMinutes = null) {
try {
const data = { value };
if (expiryMinutes) {
data.expiry = Date.now() + expiryMinutes * 60 * 1000; // Convert minutes to ms
}
this.storage.setItem(key, JSON.stringify(data));
} catch (error) {
console.error("Error setting localStorage item:", error);
}
}
// β
Get item (returns default value if key is missing)
getItem(key, defaultValue = null) {
try {
const item = this.storage.getItem(key);
if (!item) return defaultValue;
const data = JSON.parse(item);
if (data.expiry && Date.now() > data.expiry) {
this.removeItem(key); // Auto-remove expired items
return defaultValue;
}
return data.value;
} catch (error) {
console.error("Error reading localStorage item:", error);
return defaultValue;
}
}
// β
Remove item
removeItem(key) {
this.storage.removeItem(key);
}
// β
Clear all storage
clear() {
this.storage.clear();
}
// β
Get all keys
getAllKeys() {
return Object.keys(this.storage);
}
}
// β
Usage
const storage = new StorageHelper(); // Uses `localStorage` by default
storage.setItem("user", { name: "Ravi", age: 24 });
console.log(storage.getItem("user")); // Output: { name: "Ravi", age: 24 }
storage.setItem("temp", "expires in 1 min", 1);
console.log(storage.getItem("temp")); // Output: "expires in 1 min" (before expiry)
setTimeout(() => {
console.log(storage.getItem("temp")); // Output: null (after expiry)
}, 60000);
π Why Use This Wrapper?
β
No more manual JSON.parse()
and JSON.stringify()
β
Prevents errors from malformed JSON
β
Handles expiration automatically
β
Works with both localStorage
and sessionStorage
β
Provides a cleaner and safer API
Would you like a React Hook version for seamless integration? π―