Tutorial — your first storage instance
Ten minutes: install, save a value, read it back, then optionally use a TTL policy.
Previous: Overview · Next: Core concepts
Playground
Prefer clicking over coding first? Open the Storage Lab and use Set / Get — same ideas as below.
Prerequisites: a browser or Node app that can import ESM / TypeScript.
Who is this for?
| Path | After this tutorial |
|---|---|
| Beginner | Read Concepts, then copy a Recipe |
| Experienced | Skim steps 2–3, jump to Core for options / migrate |
Step 1 — Install
npm install @jayoncode/storage(pnpm add / yarn add work the same — see Overview → Install.)
Outcome: You can import from @jayoncode/storage.
Step 2 — Create a store (memory)
Memory is perfect for learning — nothing touches the real browser yet.
import { createStorage, createMemoryAdapter } from "@jayoncode/storage";
const storage = createStorage({
namespace: "demo",
adapter: createMemoryAdapter(),
});Outcome: A sync API bound to the demo namespace.
Going to production later
Swap createMemoryAdapter() for createLocalStorageAdapter() (survive reload) or createSessionStorageAdapter() (tab only). Details: Core → Adapters.
Step 3 — Save and load
storage.set("greeting", "hello");
storage.get("greeting"); // "hello"
storage.has("greeting"); // true
storage.remove("greeting");
storage.get("greeting"); // nullOutcome: Round-trip works. Missing keys return null (not a thrown error).
Optional: peek at metadata
storage.set("greeting", "hello");
storage.peek("greeting");
// { v: 1, schemaVersion: "1", savedAt: …, value: "hello", expiresAt?: … }Beginners can ignore peek until they care about expiry or schema version.
Step 4 — Add expiry (optional)
Option A — one-off TTL on the write
storage.set("flash", "soon gone", { ttl: { minutes: 5 } });Option B — named policy (reusable)
const storage = createStorage({
namespace: "demo",
adapter: createMemoryAdapter(),
policies: {
cache: { ttl: { minutes: 15 } },
},
});
storage.set("feed", { items: [] }, { policy: "cache" });Outcome: Values can expire. After expiry, get returns null (Storage deletes the stale entry when you read it).
Watch the countdown in the Lab’s TTL page.
Step 5 — Clean up keys
storage.remove("feed"); // one key
// storage.clear(); // entire namespace (needs adapter.keys — built-ins have it)Outcome: You know how to delete data on purpose.
Checkpoint — you now know
- [x] Create a namespaced store
- [x]
set/get/remove - [x] Soft
nullwhen missing - [x] Optional TTL / policies
What’s next
| Goal | Page |
|---|---|
| Understand envelopes & adapters | Core concepts |
| Copy prefs / cache patterns | Recipes |
| Full option tables | Core |
| Quota / typed errors | Errors |
| Sweep / backup / watch (advanced) | Maintenance onward |
