Skip to content

$cache

A utility toolkit for interacting with IndexedDB for persistent, client-side storage.

Initialization

This module uses idb under the hood and creates an IndexedDB store named "$cache" with a single object store called "cache".

ts
const db = await openDB("$cache", 1, {
    upgrade(db) {
        if (!db.objectStoreNames.contains("cache")) {
            db.createObjectStore("cache")
        }
    },
})

API

set(key: string, value: any)

Stores a value under the specified key in the cache. Triggers listeners in CacheListeners.check().

ts
await $cache.set("user-profile", { name: "Cody" })

get<T>(key: string): Promise<T | undefined>

Retrieves a value by key.

ts
const user = await $cache.get<User>("user-profile")

has(key: string): Promise<boolean>

Returns true if the key exists in the cache.

ts
if (await $cache.has("auth-token")) {
    // token exists
}

delete(key: string): Promise<void>

Deletes a key from the cache.

ts
await $cache.delete("user-settings")

clear(): Promise<void>

Clears all keys and values from the cache.

ts
await $cache.clear()

keys(): Promise<string[]>

Returns all keys currently stored in the cache.

ts
const allKeys = await $cache.keys()

values<T>(): Promise<T[]>

Returns all values currently stored.

ts
const users = await $cache.values<User>()

entries<T>(): Promise<[string, T][]>

Returns all key-value pairs.

ts
const pairs = await $cache.entries<User>()

size(): Promise<number>

Returns the number of items in the cache.

ts
const count = await $cache.size()

uncache(key: string, ref: Ref<any>)

Mounts a value from cache into a Vue ref. If no value is found, sets it to null.

ts
const profile = ref(null)
await $cache.uncache("user-profile", profile)

bus

A named event bus ("$cache") used for reactive state or cross-component communication.

ts
$cache.bus.on("update", () => { ... })
$cache.bus.emit("update")

Notes

  • Always use await when calling $cache methods.
  • All operations are async and safe to use in Nuxt lifecycle hooks or composables.
  • IndexedDB has ~50MB quota in most modern browsers.

Example

ts
await $cache.set("theme", "dark")
const theme = await $cache.get("theme")
  • $bus – Emits and listens to named events for this cache namespace.