Lockr: LocalStorage Wrapper
Lockr is an extremely lightweight JavaScript library (<2KB minified) designed to simplify interactions with the browser's `localStorage` API. It provides a Redis-like API for storing various data types, including strings, numbers, objects, and arrays, and offers set-like operations (e.g., `sadd`, `smembers`, `sismember`, `srem`). It is currently in a beta phase, with version 0.9.0-beta.2, indicating ongoing development. While no explicit release cadence is stated, the active development and beta tag suggest regular updates towards a stable release. Its primary differentiator is its automatic object serialization/deserialization and its distinct Redis-inspired API for managing collections, moving beyond the simple key-value string storage of native `localStorage` and offering a more feature-rich experience.
Common errors
-
ReferenceError: localStorage is not defined
cause Attempting to use Lockr in a non-browser environment (e.g., Node.js, server-side rendering) where the global `localStorage` object is not available.fixEnsure your code only runs Lockr in a browser context. For SSR, conditionally import/execute Lockr or use a `localStorage` polyfill for Node.js if necessary for testing purposes. -
DOMException: QuotaExceededError
cause The application has attempted to store more data than the browser's `localStorage` quota allows (typically 5-10MB per origin).fixReview the data being stored and reduce its size. Consider compressing data before storing, or use alternative storage solutions like IndexedDB for larger datasets. -
Lockr.get('key') returns undefined instead of null for non-existent keys.cause Developers accustomed to native `localStorage.getItem('key')` which returns `null` for non-existent keys might expect the same from Lockr. `Lockr.get` returns `undefined`.fixAdjust your code to check for `undefined` instead of `null` when retrieving potentially non-existent keys with `Lockr.get`. Alternatively, use the second argument of `Lockr.get(key, defaultValue)` to provide a fallback. -
Data saved with Lockr.set is not accessible via localStorage.getItem() directly.
cause Lockr serializes objects and arrays to JSON strings and often stores them with internal metadata (e.g., `{"data": "value"}`). If `Lockr.prefix` is set, the key stored in `localStorage` will also be different.fixAlways retrieve data using `Lockr.get(key)` to ensure proper deserialization and key prefix handling. Avoid directly accessing `localStorage.getItem()` for data managed by Lockr unless you understand its internal storage format.
Warnings
- gotcha The package is currently in a beta release (0.9.0-beta.2). While functional, it may contain bugs or introduce breaking changes before a stable 1.0.0 release. It is generally not recommended for critical production systems without thorough testing.
- gotcha When `Lockr.prefix` is set, methods like `Lockr.flush()` and `Lockr.getAll()` will *only* operate on keys that match the configured prefix. Keys stored without the prefix (e.g., via direct `localStorage.setItem` or before the prefix was set) will be ignored by these operations.
- gotcha Lockr relies on the browser's native `localStorage` API. If `localStorage` is unavailable (e.g., in private browsing mode, some older browsers, or when running in a Node.js environment without a `localStorage` polyfill), Lockr operations will fail or throw errors without graceful degradation.
- gotcha Lockr (and native `localStorage`) operates synchronously, which can block the main thread for large data operations. It also has limited storage capacity (typically 5-10MB per origin) and stores data as strings, requiring serialization/deserialization.
Install
-
npm install lockr -
yarn add lockr -
pnpm add lockr
Imports
- Lockr
import { Lockr } from 'lockr'import Lockr from 'lockr'
- Lockr (CommonJS)
const Lockr = require('lockr') - Lockr (Namespace Import)
import * as Lockr from 'lockr'
Quickstart
import Lockr from 'lockr';
// Set a prefix for all keys (optional, but good practice)
Lockr.prefix = 'my_app_data_';
// Store various data types. Lockr automatically serializes objects and arrays.
Lockr.set('username', 'Alice Smith');
Lockr.set('userId', 42);
Lockr.set('settings', { theme: 'dark', notifications: true });
Lockr.set('favoriteFruits', ['apple', 'banana', 'cherry']);
// Retrieve values. Lockr automatically deserializes them.
console.log('Username:', Lockr.get('username'));
// Expected: Username: Alice Smith
console.log('Settings:', Lockr.get('settings'));
// Expected: Settings: { theme: 'dark', notifications: true }
// Use Redis-like set operations (sadd, smembers)
Lockr.sadd('uniqueTags', 'javascript');
Lockr.sadd('uniqueTags', 'typescript');
Lockr.sadd('uniqueTags', 'javascript'); // Adding again has no effect
console.log('Unique Tags:', Lockr.smembers('uniqueTags'));
// Expected: Unique Tags: [ 'javascript', 'typescript' ]
// Remove a key
Lockr.rm('username');
console.log('Username after removal:', Lockr.get('username', 'Guest'));
// Expected: Username after removal: Guest (demonstrating default value)
// Get all values (only prefixed ones if prefix is set)
console.log('All stored values:', Lockr.getAll());