惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

C
CXSECURITY Database RSS Feed - CXSecurity.com
aimingoo的专栏
aimingoo的专栏
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
D
Docker
博客园 - 叶小钗
Recent Announcements
Recent Announcements
人人都是产品经理
人人都是产品经理
云风的 BLOG
云风的 BLOG
Vercel News
Vercel News
Hugging Face - Blog
Hugging Face - Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
美团技术团队
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
F
Fortinet All Blogs
博客园 - 三生石上(FineUI控件)
Microsoft Security Blog
Microsoft Security Blog
H
Heimdal Security Blog
有赞技术团队
有赞技术团队
The Cloudflare Blog
S
Secure Thoughts
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
T
The Blog of Author Tim Ferriss
M
MIT News - Artificial intelligence
Google DeepMind News
Google DeepMind News
Schneier on Security
Schneier on Security
N
News and Events Feed by Topic
小众软件
小众软件
C
Cybersecurity and Infrastructure Security Agency CISA
Application and Cybersecurity Blog
Application and Cybersecurity Blog
博客园 - Franky
T
Tenable Blog
The Last Watchdog
The Last Watchdog
腾讯CDC
量子位
Google DeepMind News
Google DeepMind News
Help Net Security
Help Net Security
雷峰网
雷峰网
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Cyberwarzone
Cyberwarzone
S
Securelist
Martin Fowler
Martin Fowler
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
罗磊的独立博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
P
Proofpoint News Feed
D
Darknet – Hacking Tools, Hacker News & Cyber Security
I
InfoQ
Spread Privacy
Spread Privacy
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
H
Hackread – Cybersecurity News, Data Breaches, AI and More

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Stokado: A Zero-Dependency Proxy Wrapper That Makes Browser Storage Feel Like a Plain Object
KID-joker · 2026-06-24 · via DEV Community

If you've shipped anything to the browser, you've used localStorage. And if you've used it for more than five minutes, you've also written this exact line more times than you'd like to admit:

const user = JSON.parse(localStorage.getItem('user') || 'null')

The Web Storage API has aged remarkably well for something so small, but it carries three persistent pain points that every frontend codebase ends up papering over by hand.

Pain point #1: everything is a string. localStorage.setItem('count', 0) doesn't store the number 0 — it stores the string "0". Read it back and typeof is "string". Booleans become "true"/"false", Date objects collapse into ISO strings (if you're lucky) or "[object Object]" (if you're not), and undefined becomes the literal string "undefined". So every project grows a thin serialization layer of JSON.parse/JSON.stringify wrappers, plus a pile of defensive try/catch blocks for the day a malformed value sneaks in.

Pain point #2: the API is verbose and stringly-typed. getItem, setItem, removeItem — three method calls and a string key for what is conceptually just reading and writing a property. It reads nothing like the rest of your code.

Pain point #3: reactivity is broken in the tab you actually care about. The native storage event only fires in other tabs of the same origin. The tab that performed the write never hears about it. So if you want to react to your own storage changes — the overwhelmingly common case — the platform gives you nothing.

Stokado is a small, zero-dependency library that addresses all three by wrapping any storage object in a Proxy. It's framework-agnostic, TypeScript-friendly, and works equally well with localStorage, sessionStorage, cookies, async backends like localForage, and a handful of mini-program runtimes. This article walks through what it actually does, feature by feature, with runnable code.


Quick start

npm install stokado

import { createProxyStorage } from 'stokado'

const storage = createProxyStorage(localStorage)

// Write like a plain object
storage.token = 'abc'

// Read like a plain object
console.log(storage.token) // 'abc'

// Delete with the delete operator
delete storage.token

createProxyStorage takes any storage-like object and returns a proxy that behaves like a plain object on the surface, while doing serialization, change notification, expiration, and quota bookkeeping underneath. That's the whole mental model. Everything below is a refinement of it.


Type-safe serialization

The single most repetitive chore with native storage is converting values to and from strings. Stokado handles it transparently — and crucially, it preserves the type, not just the shape.

import { createProxyStorage } from 'stokado'

const storage = createProxyStorage(localStorage)

storage.count = 0
storage.enabled = false
storage.missing = null
storage.createdAt = new Date('2024-01-01T00:00:00Z')
storage.pattern = /^\d+$/g
storage.profile = { name: 'Ada', roles: ['admin'] }

console.log(typeof storage.count) // 'number'  (not "0")
console.log(storage.enabled === false) // true     (not "false")
console.log(storage.missing) // null     (not "null")
console.log(storage.createdAt instanceof Date) // true
console.log(storage.pattern.test('42')) // true
console.log(storage.profile.roles[0]) // 'admin'

The trap that catches naive JSON.parse wrappers is the falsy-but-valid value: storage.count = 0 round-trips as the number 0, not the string "0" and not undefined. The same holds for false and null. Stokado records the original type tag at write time and reconstructs the matching JavaScript value at read time.

The supported type set is deliberately broad. In addition to the obvious string, number, boolean, null, undefined, object, and array, stokado round-trips BigInt, Date, RegExp, URL, Set, Map, and even Function:

storage.id = 9007199254740993n
storage.tags = new Set(['a', 'b', 'a'])
storage.lookup = new Map([['x', 1]])
storage.api = new URL('https://example.com/v1')
storage.greet = function (name) {
  return `hi ${name}`
}

console.log(typeof storage.id) // 'bigint'
console.log(storage.tags instanceof Set) // true
console.log(storage.lookup.get('x')) // 1
console.log(storage.api.host) // 'example.com'
console.log(storage.greet('Ada')) // 'hi Ada'

A note on Function: stokado serializes it via toString() and rebuilds it with the Function constructor on read. That's genuinely useful for storing small configuration callbacks, but be aware it relies on dynamic evaluation and loses closure scope — treat it as a convenience for trusted, self-contained functions rather than a general serialization mechanism.

If you ever need the raw conversion outside of a proxy, stokado exports the underlying encode and decode functions directly:

import { decode, encode } from 'stokado'


Same-tab reactive subscriptions

This is where stokado earns its keep. You can subscribe to changes on a specific key, and — unlike the native storage event — the callback fires in the same tab that made the change.

import { createProxyStorage } from 'stokado'

const storage = createProxyStorage(localStorage)

storage.on('token', (newValue, oldValue) => {
  console.log(`token changed: ${oldValue} -> ${newValue}`)
})

storage.token = 'abc' // logs: token changed: undefined -> abc
storage.token = 'xyz' // logs: token changed: abc -> xyz

Every listener receives (newValue, oldValue), both already deserialized to their proper types. There are three methods:

  • on(key, fn) — subscribe to all future changes for key.
  • once(key, fn) — fire exactly once, then auto-unsubscribe.
  • off(key?, fn?) — unsubscribe. Pass a key and function to remove one listener, pass just a key to remove all listeners for that key, or pass nothing to clear everything.
function handler(n, o) {
  console.log('once:', n, o)
}

storage.once('session', handler)
storage.session = 'first' // fires once
storage.session = 'second' // silent — already unsubscribed

storage.on('cart', updateBadge)
storage.off('cart', updateBadge) // remove a single listener

Subscriptions even reach into nested properties using dot paths, which is handy when you store structured objects:

storage.on('profile.name', (n, o) => console.log(`name: ${o} -> ${n}`))

storage.profile = { name: 'Ada' }
storage.profile.name = 'Grace' // logs: name: Ada -> Grace

Because this works in the same tab, you can use storage as a lightweight intra-app event bus — for example, keeping a header avatar in sync with a settings page without reaching for a global store.


Expiration and disposable values

Native storage has no concept of a TTL. Stokado adds two complementary lifetime controls through the third argument of setItem.

import { createProxyStorage } from 'stokado'

const storage = createProxyStorage(localStorage)

// Expires at a specific time (timestamp or Date)
storage.setItem('session', 'token-123', {
  expires: Date.now() + 60_000, // gone in 60 seconds
})

// Disposable: self-destructs after the first read
storage.setItem('flash', 'You just signed in!', {
  disposable: true,
})

console.log(storage.flash) // 'You just signed in!'
console.log(storage.flash) // undefined — consumed on first read

expires accepts a timestamp, a date string, or a Date instance. Once the moment passes, the value is treated as gone — reading it returns undefined and the entry is cleaned up. disposable is a one-shot read: perfect for flash messages, single-use tokens, or any "show this exactly once" value.

The two can be combined, and there's a small family of helpers for managing lifetimes after the fact:

// Set / inspect / clear an expiry on an existing key
storage.setExpires('session', new Date('2030-01-01'))
console.log(storage.getExpires('session')) // Date instance
storage.removeExpires('session')

// Mark an existing key as disposable
storage.setDisposable('flash')

// Inspect the full option set for a key
console.log(storage.getOptions('session'))
// e.g. { expires: <Date>, disposable: true } — or null if no options set

getOptions returns whatever lifetime metadata is attached to a key (expires, disposable, or both), or null if the key is a plain value. It's a clean way to introspect state without guessing.


Cross-tab synchronization

Same-tab reactivity is great, but sometimes you genuinely want every open tab to agree. Stokado can broadcast changes across tabs of the same origin using the BroadcastChannel API.

import { createProxyStorage } from 'stokado'

const storage = createProxyStorage(localStorage, {
  broadcast: true,
  channel: 'app-storage',
})

// In any tab:
storage.on('theme', (next) => {
  document.documentElement.dataset.theme = next
})

// In another tab:
storage.theme = 'dark' // every tab's listener fires

With broadcast enabled, a write in one tab propagates over the named channel and triggers your subscriptions in the others — so your same-tab on/once handlers and your cross-tab handlers share one unified API. The channel option lets you scope the broadcast so unrelated proxies don't talk over each other.


Quota alerts

Web Storage throws a QuotaExceededError when you exceed the (browser-dependent, typically ~5 MB) limit, and by then it's too late. Stokado lets you set a soft quota and get a callback before a write lands.

import { createProxyStorage, MB } from 'stokado'

const storage = createProxyStorage(localStorage, {
  quota: 4 * MB,
  onQuotaExceeded(info) {
    console.warn(
      `Quota hit on "${info.key}": ${info.current}/${info.limit} bytes`,
    )
    // Return false to block this write entirely
    return false
  },
})

The callback receives a QuotaInfo object with { current, limit, key, value } — the projected total size, your configured limit, and the key/value being written. The return value controls the write:

  • Return false to reject the write (the value is not stored).
  • Return anything else (or nothing) to allow it.

The handler may also be async, which is useful when you want to evict old entries or ask the user before deciding:

const storage = createProxyStorage(localStorage, {
  quota: 4 * MB,
  async onQuotaExceeded(info) {
    const proceed = await confirmWithUser(info)
    return proceed // false blocks, true allows
  },
})

For proactive monitoring, getUsage() reports current consumption against the limit at any time:

const { current, limit } = storage.getUsage()
console.log(`Using ${current} of ${limit} bytes`)

Stokado measures byte size accurately (via Blob), so the numbers reflect real UTF-8 encoded sizes rather than naive string lengths. The exported KB and MB constants are just 1024 and 1024 * 1024 to keep your quota declarations readable.


Async backends

localStorage caps out around 5 MB and is synchronous. For larger or non-blocking storage, localForage is the go-to — it transparently uses IndexedDB and exposes a Promise-based API. Stokado proxies it just as happily, returning an AsyncProxyStorage whose methods return Promises.

import localforage from 'localforage'
import { createProxyStorage } from 'stokado'

const storage = createProxyStorage(localforage)

// Wait for the backend to be ready before first use
await storage.ready

await storage.setItem('test', 'hello stokado')
console.log(await storage.test) // 'hello stokado'

await storage.removeItem('test')
console.log(await storage.test) // undefined

Stokado auto-detects that the backend is asynchronous and adapts its surface accordingly. A few differences from the sync case to keep in mind:

  • Reads and writes resolve to Promises, so you await them (await storage.test, await storage.setItem(...)).
  • ready is a Promise you can await to ensure the backend has finished initializing.
  • length() is a method that returns a Promise, not a synchronous property.
  • getUsage() returns a Promise.

Everything else — type preservation, subscriptions, expiration, disposable values — works identically. The same setItem('key', value, { expires, disposable }), the same on/once/off, just with await where the platform forces it.


Multi-platform presets

Browser localStorage is only one of many key-value stores in the JavaScript world. Stokado ships seven ready-made presets as sub-path imports, each adapting a foreign storage API to the shape createProxyStorage expects. Import only the one you need — they're tree-shakeable.

Cookies — a Storage-like view over document.cookie:

import { createProxyStorage } from 'stokado'
import { cookieStorage } from 'stokado/presets/cookie'

const cookies = createProxyStorage(cookieStorage)
cookies.consent = true

WeChat / Douyin / Alipay mini-programs — each exposes both a sync and an async variant mapping to that platform's storage SDK:

import { createProxyStorage } from 'stokado'
import { wechatStorage, wechatStorageAsync } from 'stokado/presets/wechat'
import { douyinStorage, douyinStorageAsync } from 'stokado/presets/douyin'
import { alipayStorage, alipayStorageAsync } from 'stokado/presets/alipay'

const wx = createProxyStorage(wechatStorage)

uni-app — the cross-platform mini-program framework, again sync and async:

import { createProxyStorage } from 'stokado'
import { uniStorage, uniStorageAsync } from 'stokado/presets/uni-app'

const uni = createProxyStorage(uniStorage)

React Native — wrap @react-native-async-storage/async-storage (or any compatible AsyncStorage) into an async storage-like object:

import AsyncStorage from '@react-native-async-storage/async-storage'
import { createProxyStorage } from 'stokado'
import { createReactNativeStorage } from 'stokado/presets/react-native'

const storage = createProxyStorage(createReactNativeStorage(AsyncStorage))
await storage.ready
await storage.setItem('token', 'abc')

Node — an in-memory store, ideal for tests, SSR, and CLI tools where no browser storage exists:

import { createProxyStorage } from 'stokado'
import { memoryStorage } from 'stokado/presets/node'

const storage = createProxyStorage(memoryStorage)
storage.cached = { ok: true }

Because the presets normalize everything to the same storage-like interface, the entire stokado feature set — serialization, subscriptions, expiration — works the same across all of them. Write your data layer once, run it on the web, in a mini-program, in React Native, or on the server.


How it compares

Stokado is not trying to be the only storage tool you'll ever need, and it's worth being honest about where other libraries are the better pick.

  • If your priority is squeezing data into a smaller footprint, reach for lz-string. It's purpose-built for compressing strings before they hit storage. Stokado focuses on faithful type round-tripping, not compression.
  • If you live entirely in Vue and want storage wired into the reactivity system, useStorage from @vueuse/core gives you a ref that syncs to storage with deep Vue integration. Stokado is framework-agnostic by design and won't give you a Vue ref out of the box.
  • If you need a large IndexedDB-backed key-value store and nothing else, idb-keyval is a tiny, focused option. (And if you want stokado's features on top of IndexedDB, recall that it proxies localForage, which sits on IndexedDB.)

Where stokado's edge shows is the combination: faithful type preservation and same-tab reactivity and expiration/disposable values and quota awareness, all behind one plain-object interface, with zero dependencies and the same API across browsers, mini-programs, React Native, and Node. No single feature is unique; having all of them composed together, with nothing to install but the package itself, is.


Wrap-up

The Web Storage API gives you a synchronous string-to-string map and not much else. Stokado keeps that simplicity at the surface — storage.token = 'abc' — while quietly handling the parts every team reimplements: type-correct serialization, same-tab change subscriptions, TTLs and one-shot values, cross-tab sync, and quota guards. And it does it without dragging in a single dependency, across every JavaScript runtime that has a key-value store.

If you've been hand-rolling JSON.parse wrappers and storage event workarounds, give it a try:

npm install stokado

import { createProxyStorage } from 'stokado'

const storage = createProxyStorage(localStorage)
storage.user = { name: 'Ada', lastSeen: new Date() }

The full source, tests, and API reference live at github.com/KID-joker/stokado.