nano-safe-storage
v1.0.0
Published
A fault-tolerant, zero-dependency, nano-sized wrapper for the browser's localStorage API with automatic JSON serialization.
Maintainers
Readme
nano-safe-storage 🛡️
A fault-tolerant, zero-dependency, nano-sized wrapper for the browser's localStorage API.
nano-safe-storage solves the headache of using localStorage in production apps. It handles JSON serialization, storage quotas, and security restrictions (Private Mode) automatically, so your app never crashes.
🚀 Why use this?
Using localStorage directly works fine in development, but fails in production:
- JSON Errors:
getItemreturns a string. You have to manuallyJSON.parse()it. If the data is corrupted (e.g., user edited cookies), your app crashes. - Quota Exceeded: If the user's storage is full,
setItemthrows aQuotaExceededError. - Private Mode: In Safari Private Mode or embedded iframes, accessing
localStoragethrows aSecurityError.
nano-safe-storage handles all of this for you.
Comparison
❌ The Hard Way (Native)
try {
const data = JSON.stringify(value);
localStorage.setItem('key', data);
} catch (e) {
if (e.name === 'QuotaExceededError') {
// Handle full storage...
} else if (e.name === 'SecurityError') {
// Handle private mode...
}
}
try {
const item = localStorage.getItem('key');
const parsed = item ? JSON.parse(item) : null;
} catch (e) {
// Handle JSON parse error...
}✅ The Easy Way (nano-safe-storage)
import { setItem, getItem } from 'nano-safe-storage';
setItem('key', { foo: 'bar' }); // Safely handles full storage & private mode
const data = getItem('key'); // Safely handles parsing & null checks✨ Features
- 🛡️ Fault Tolerant: Wraps every operation in
try/catch. Never crashes your app. - 🔄 Auto Serialization: Automatically
JSON.stringifyon save andJSON.parseon load. - 👻 In-Memory Fallback: If
localStorageis disabled or broken (e.g., SecurityError), it silently stores data in memory so your app keeps working (per-session). - 📦 Zero Dependencies: Pure JavaScript. No bloat.
- ⚡ Nano Sized: < 1kb (minified + gzipped).
- 🔌 TypeScript Compatible: Includes a professional
index.d.tswith Generics.
📦 Installation
npm install nano-safe-storage🛠️ Usage
Basic Usage
import { setItem, getItem, removeItem, clear } from 'nano-safe-storage';
// Save an object (automatically stringified)
setItem('user_profile', { id: 123, name: 'Alice', theme: 'dark' });
// Retrieve an object (automatically parsed)
const profile = getItem('user_profile');
console.log(profile.name); // 'Alice'
// Remove specific item
removeItem('user_profile');
// Clear all data
clear();TypeScript Usage
Use Generics to define the return type of getItem.
import { getItem } from 'nano-safe-storage';
interface UserSettings {
theme: 'light' | 'dark';
notifications: boolean;
}
// typedSettings is UserSettings | null
const typedSettings = getItem<UserSettings>('settings');
if (typedSettings) {
console.log(typedSettings.theme);
}Handling Failures
Quota Exceeded:
If setItem fails because storage is full, it catches the error, logs a warning to the console, and prevents the app from crashing.
Corrupted Data:
If getItem encounters invalid JSON (e.g. "{ bad json }), it catches the SyntaxError, logs an error, and returns null.
Private Mode:
If localStorage is unavailable due to browser security settings, the library automatically switches to an in-memory storage. Data will persist for the session but clear on refresh.
🤝 Contributing
Contributions are welcome!
- Fork the Project
- Create your Feature Branch (
git checkout -b feature/AmazingFeature) - Commit your Changes (
git commit -m 'Add some AmazingFeature') - Push to the Branch (
git push origin feature/AmazingFeature) - Open a Pull Request
📄 License
Distributed under the MIT License. See LICENSE for more information.
Author: Arnel Robles Repository: github.com/BaryoDev/nano-safe-storage
