browser-storage-utils
v1.0.2
Published
A lightweight utility library for browser storage operations
Maintainers
Readme
Storage Utils
A lightweight, type-safe TypeScript/JavaScript library for handling browser storage with a consistent API across different storage mechanisms.
Features
- Cookie Storage - Simple cookie management with expiration, domain, and secure options
- Local Storage - Persistent key-value storage with prefix support
- Session Storage - Session-based key-value storage with prefix support
- Type Safety - Built with TypeScript for better developer experience
- SSR Support - Safe to use in server-side rendering environments
- Modular - Import only what you need
Installation
npm install storage-utils
# or
yarn add storage-utilsUsage
Importing
// Import specific utilities as needed
import {
// Cookie functions
setCookie,
getCookie,
removeCookie,
// Local Storage
getLocalItem,
setLocalItem,
removeLocalItem,
clearLocalStorage,
getLocalKeys,
// Session Storage
getSessionItem,
setSessionItem,
removeSessionItem,
clearSessionStorage,
getSessionKeys
} from 'storage-utils';Cookie Storage
// Set a cookie
setCookie('theme', 'dark', {
expires: 7, // days
path: '/',
secure: true,
sameSite: 'Lax'
});
// Get a cookie
const theme = getCookie('theme'); // 'dark'
// Remove a cookie
removeCookie('theme');Local Storage
// Set an item with prefix
setLocalItem('user', { name: 'John', id: 1 }, { prefix: 'app_' });
// Get an item
const user = getLocalItem('user', { prefix: 'app_' });
// Get all keys with prefix
const keys = getLocalKeys({ prefix: 'app_' });
// Remove an item
removeLocalItem('user', { prefix: 'app_' });
// Clear all items with prefix
clearLocalStorage({ prefix: 'app_' });Session Storage
// Set an item with prefix
setSessionItem('token', 'abc123', { prefix: 'auth_' });
// Get an item
const token = getSessionItem('token', { prefix: 'auth_' });
// Clear all session storage
clearSessionStorage();API Reference
Common Options
All storage methods accept an optional options object that can include:
prefix?: string- Optional prefix for key namespacing
Cookie Specific Options
interface CookieOptions {
expires?: number | Date; // days or Date object
path?: string;
domain?: string;
secure?: boolean;
sameSite?: 'Strict' | 'Lax' | 'None';
prefix?: string;
}Browser Support
This library works in all modern browsers including:
- Chrome 49+
- Firefox 44+
- Safari 10.1+
- Edge 16+
- Opera 36+
License
MIT
