Skip to content

Key-Value Storage (@microfn/kv)

The @microfn/kv module allows you to store and retrieve data that persists across function executions. It’s perfect for caching, user preferences, session data, and any state that needs to survive between runs.

import kv from "@microfn/kv";
// Write to the key-value store
await kv.set("my-key", { message: "Hello World" });
// Read from the key-value store
const value = await kv.get("my-key");

Here are a few useful things you can do with @microfn/kv:

Avoid hitting external APIs on every request by caching responses for a specific duration.

export async function main({ url }) {
const key = `cache:${url}`;
const cached = await kv.get<{ data: any; ts: number }>(key).catch(() => null);
// Return cached data if it's less than an hour old
if (cached && Date.now() - cached.ts < 3_600_000) {
return { ...cached, fromCache: true };
}
// Fetch fresh data and cache it
const res = await fetch(url);
const data = await res.json();
await kv.set(key, { data, ts: Date.now() });
return { data, fromCache: false };
}

Track hits for a specific route or event.

export async function main({ route }) {
const key = `hits:${route}`;
const currentHits = (await kv.get<number>(key).catch(() => 0)) + 1;
await kv.set(key, currentHits);
return { route, hits: currentHits };
}

Save user-specific settings that can be retrieved later.

export async function main({ userId, prefs }) {
const key = `user:${userId}:prefs`;
await kv.set(key, prefs);
const savedPrefs = await kv.get(key);
return { success: true, saved: savedPrefs };
}