npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

safe-storage-ts

v1.0.1

Published

Zero-dependency, type-safe browser storage wrapper (localStorage & sessionStorage) with TTL expiry, SSR memory fallback, namespace prefixes, and change listeners.

Readme

🛡️ safe-storage-ts

Zero-dependency, type-safe browser storage wrapper (localStorage & sessionStorage) with TTL expiry, SSR memory fallback, namespace prefixes, and change listeners.

npm version License: MIT Sponsor TypeScript


✨ Features

  • 🔒 Full Type-Safety — Seamless generics storage.get<User>('user') for objects, arrays, numbers, and booleans.
  • ⏳ TTL & Automatic Expiry — Set expiration in seconds or with a Date object; expired entries are purged automatically.
  • 🌐 SSR & Incognito Safe — Gracefully falls back to an in-memory storage backend if window, localStorage, or quota is unavailable.
  • 🏷️ Namespaces & Prefixing — Isolate storage keys easily across different features, apps, or multi-tenant sessions.
  • 📡 Reactive Listeners — Subscribe to key changes across tabs or locally with .subscribe(key, (newVal, oldVal) => ...).
  • ⚡ Zero Dependencies — Ultra-lightweight (~2 KB minified), purely native TypeScript.
  • 📦 Dual ESM & CommonJS — Compatible with Next.js, Nuxt, Remix, Vite, React, Node.js, and vanilla apps.

📥 Installation

npm install safe-storage-ts

or with Yarn / pnpm:

pnpm add safe-storage-ts
# or
yarn add safe-storage-ts

🚀 Quick Start

1. Simple Type-Safe Storage

import { safeLocalStorage } from 'safe-storage-ts';

interface UserProfile {
  id: string;
  name: string;
  email: string;
}

// Store an object directly (no manual JSON.stringify needed)
safeLocalStorage.set('profile', {
  id: 'usr_123',
  name: 'Alex Doe',
  email: '[email protected]',
});

// Retrieve with complete TypeScript type inference
const user = safeLocalStorage.get<UserProfile>('profile');
console.log(user?.name); // Alex Doe

2. Time-To-Live (TTL) & Expiry

Auto-expire tokens, cache responses, or sessions after a set duration:

import { safeLocalStorage } from 'safe-storage-ts';

// Expire after 3600 seconds (1 hour)
safeLocalStorage.set('auth_token', 'xyz-secret-token', { ttl: 3600 });

// Or shorthand number:
safeLocalStorage.set('temp_banner_dismissed', true, 86400); // 24 hours

// Check remaining seconds before expiration:
const remainingSecs = safeLocalStorage.getRemainingTTL('auth_token');
console.log(`Token expires in ${remainingSecs} seconds`);

// Once expired, get() automatically purges the item and returns null or fallback:
const token = safeLocalStorage.get('auth_token', null);

3. Isolated Namespaces & Prefixing

Prevent key collisions by creating dedicated storage scopes:

import { createStorage } from 'safe-storage-ts';

const authStorage = createStorage({
  type: 'localStorage',
  prefix: 'app_auth_',
});

const cartStorage = createStorage({
  type: 'sessionStorage',
  prefix: 'app_cart_',
});

authStorage.set('token', 'secret123'); // Stored as "app_auth_token"
cartStorage.set('items', ['apple', 'orange']); // Stored as "app_cart_items" in sessionStorage

// Clear only cart items without affecting auth:
cartStorage.clear();

4. Reactive Change Listeners

Listen to updates on specific keys:

import { safeLocalStorage } from 'safe-storage-ts';

const unsubscribe = safeLocalStorage.subscribe('theme', (newTheme, oldTheme) => {
  console.log(`Theme changed from ${oldTheme} to ${newTheme}`);
  document.documentElement.setAttribute('data-theme', newTheme);
});

// Update value
safeLocalStorage.set('theme', 'dark');

// Stop listening when component unmounts
unsubscribe();

⚙️ API Reference

createStorage(options)

| Option | Type | Default | Description | |---|---|---|---| | type | 'localStorage' \| 'sessionStorage' \| 'memory' | 'localStorage' | Storage backend mechanism. | | prefix | string | '' | Prefix prepended to all stored keys. | | serializer | (val: unknown) => string | JSON.stringify | Custom string serializer. | | deserializer | (str: string) => unknown | JSON.parse | Custom parser. | | onError | (err, action) => void | undefined | Error hook for storage exceptions (quota, etc.). |


SafeStorage Methods

| Method | Return Type | Description | |---|---|---| | set<T>(key, value, options?) | boolean | Stores a value with optional { ttl } or { expiresAt }. | | get<T>(key, fallback?) | T \| null | Retrieves value. Purges and returns fallback if expired. | | getRemainingTTL(key) | number \| null | Returns remaining seconds until expiration, or null. | | has(key) | boolean | Checks if key exists and is unexpired. | | remove(key) | boolean | Removes specific key. | | clear() | boolean | Clears all keys belonging to this instance's prefix. | | keys() | string[] | Lists all keys (prefix stripped). | | size() | number | Count of keys stored. | | subscribe<T>(key, callback) | () => void | Listens to key updates. Returns unsubscribe function. | | isUsingMemory() | boolean | True if fallback memory storage is active. |


🛠 Development & Testing

# Install dependencies
npm install

# Run unit tests
npm test

# Build dual ESM/CJS bundles + .d.ts types
npm run build

💖 Support the Project

If you find this package useful, consider sponsoring its ongoing development and maintenance: 👉 Sponsor @Piratha97 on GitHub Sponsors

📄 License

MIT © 2026 Pirapaakaran Pirathapan