isLocalStorageAvailable
Checks if localStorage is available and functional.
1/**
2 * Checks if localStorage is available and functional.
3 *
4 * @returns True if localStorage is accessible and writable, false otherwise.
5 */
6export function isLocalStorageAvailable(): boolean {
7 try {
8 const testKey = '__localStorageTest__';
9 localStorage.setItem(testKey, 'test');
10 localStorage.removeItem(testKey);
11 return true;
12 } catch {
13 return false;
14 }
15}
Reliable Environment Detection
Accurately determines whether
localStorage
is usable, even in restricted environments like private browsing or server-side rendering.Fail-Safe Mechanism
Uses a try–catch block to prevent exceptions from breaking application flow.
Minimal Footprint
Uses a lightweight test key that is immediately cleaned up, leaving no trace in storage.
Broad Compatibility
Works consistently across all major browsers and runtime environments where
localStorage
may or may not be available.
Tests | Examples
1test('returns true when localStorage is available', () => {
2 expect(isLocalStorageAvailable()).toBe(true);
3});
4
5test('returns false when localStorage throws', () => {
6 const originalSetItem = Storage.prototype.setItem;
7 Storage.prototype.setItem = () => {
8 throw new Error('localStorage unavailable');
9 };
10
11 expect(isLocalStorageAvailable()).toBe(false);
12
13 Storage.prototype.setItem = originalSetItem;
14});
Common Use Cases
Feature Detection
Check for
localStorage
support before attempting to read or write, ensuring compatibility across browsers.Server-Side Rendering (SSR) Guards
Prevent access errors in environments where
window
orlocalStorage
isundefined
.User Privacy Mode Handling
Avoid exceptions in browsers that block
localStorage
in incognito or strict privacy modes.Progressive Enhancement
Conditionally enable localStorage-based features only when supported.
Custom Storage Fallbacks
Switch to cookies or in-memory storage when
localStorage
is unavailable.