@bantis/storage-manager
v1.0.0
Published
A comprehensive storage and cookies manager library with cross-subdomain and encryption support.
Maintainers
Readme
@bantis/storage-manager
A comprehensive, secure, and easy-to-use library for managing browser storage (localStorage, sessionStorage) and cookies. Built with TypeScript, it seamlessly integrates with frontend frameworks like React and Angular, and offers native support for client-side encryption and cross-subdomain cookie sharing.
Features
- 🔐 Built-in Encryption: Powered by
@bantis/local-cipherv2 to automatically encrypt sensitive data stored in local/session storage or cookies. - 🍪 Advanced Cookie Management: Easily set, get, and remove cookies across all paths and share them across subdomains seamlessly.
- 📦 Framework Agnostic: Works perfectly in Vanilla JS, React, Angular, Vue, etc.
- 🛡️ Type Safety: Written in TypeScript with full type definitions included.
- 🚀 Dual Exports (CJS & ESM): Bundled using
tsupto ensure compatibility with modern bundlers.
Installation
npm install @bantis/storage-manager @bantis/local-cipherSetup & Basic Usage
Unencrypted Usage
You can use the pre-instantiated exports directly out of the box if you don't need encryption:
import { localStore, sessionStore, cookies } from '@bantis/storage-manager';
// Local Storage
await localStore.set('myKey', { user: 'admin' });
const user = await localStore.get('myKey');
localStore.remove('myKey');
// Session Storage
await sessionStore.set('tempData', [1, 2, 3]);
// Cookies
await cookies.set('myTracker', 'tracker123', { expires: 7 }); // expires in 7 days
const myTracker = await cookies.get('myTracker');Encrypted Usage (Recommended for Sensitive Data)
To enable encryption, instantiate the managers with a generic secret key. @bantis/local-cipher will handle everything securely under the hood using an asynchronous API.
import { createEncryptedStorage, createEncryptedCookieManager } from '@bantis/storage-manager';
const SECRET_KEY = 'your_super_secret_key_123';
// Setup encrypted storages
const secureStore = createEncryptedStorage('localStorage', SECRET_KEY);
await secureStore.set('authToken', 'ey...');
// Value in localStorage will be securely encrypted: "sm_enc_authToken": "U2FsdGVkX1..."
const token = await secureStore.get('authToken');
// returns 'ey...'
console.log(token);
// Setup encrypted cookies with cross-subdomain support
const secureCookies = createEncryptedCookieManager(SECRET_KEY, '.yourdomain.com');
// Sets an encrypted cookie accessible across site.com, api.site.com, app.site.com
await secureCookies.set('session_id', 'unique-hash-value', {
domain: '.yourdomain.com', // ⚠️ Leading dot is important to share between subdomains
expires: 30, // valid for 30 days
});Framework Integration Examples
React Hook Example
You can easily wrap this manager in a custom React hook:
import { useState, useEffect } from 'react';
import { localStore } from '@bantis/storage-manager';
export function useLocalStore(key, initialValue) {
const [value, setValue] = useState(initialValue);
useEffect(() => {
localStore.get(key).then((saved) => {
if (saved !== null) {
setValue(saved);
} else {
localStore.set(key, initialValue);
}
});
}, [key]);
const setNewValue = async (newValue) => {
setValue(newValue);
await localStore.set(key, newValue);
};
return [value, setNewValue];
}Angular Service Example
You can wrap the encrypted manager in an injectable Angular Service:
import { Injectable } from '@angular/core';
import { createEncryptedCookieManager } from '@bantis/storage-manager';
@Injectable({
providedIn: 'root'
})
export class AuthService {
private secureCookies = createEncryptedCookieManager('my-super-secret', '.mycompany.com');
async setToken(token: string): Promise<void> {
await this.secureCookies.set('auth_token', token, { expires: 7 });
}
async getToken(): Promise<string | null> {
return await this.secureCookies.get('auth_token');
}
logout(): void {
this.secureCookies.remove('auth_token');
}
}API Reference
StorageManager
set<T>(key: string, value: T): Promise<void>get<T>(key: string): Promise<T | null>remove(key: string): Promise<void>clear(): void
CookieManager
set<T>(key: string, value: T, options?: CookieOptions): Promise<void>get<T>(key: string): Promise<T | string | null>remove(key: string, options?: Pick<CookieOptions, 'path' | 'domain'>): voidclearAll(): void
Cookie Options:
expires?: number | Date: Number of days or a specific Date object.path?: string: Cookie path, defaults to/.domain?: string: Enable cross-subdomain sharing (e.g.,.example.com).secure?: boolean: Defaults totrueon HTTPS.sameSite?: 'Strict' | 'Lax' | 'None': Defaults toLax.secretKey?: string: Required if used directly to enable encryption.
License
MIT
