convex-kv lets you use a Convex table as a key-value store with optional expiration.
npm install @raideno/convex-kvconvex/schema.ts
import { defineSchema } from "convex/server";
import { kvTables } from "@raideno/convex-kv/server";
export default defineSchema({
...kvTables,
/*
* Your app tables...
*/
});convex/kv.ts
import { internalConvexKv } from "@raideno/convex-kv/server";
export const { store, kv } = internalConvexKv();convex/actions.ts
import { action } from "./_generated/server";
import { v } from "convex/values";
import { kv } from "./kv";
export const setPreference = action({
args: {
key: v.string(),
value: v.any(),
ttlMs: v.optional(v.number()),
},
handler: async (context, args) => {
await kv.setWithExpiration(context, {
key: args.key,
value: args.value,
expiresInMs: args.ttlMs,
});
},
});
export const getPreference = action({
args: {
key: v.string(),
},
handler: async (context, args) => {
return await kv.getOrDefault(context, {
key: args.key,
defaultValue: "unset",
});
},
});kv.set(context, { key, value })kv.setWithExpiration(context, { key, value, expiresInMs? | expiresAt? })kv.get(context, { key })kv.getOrDefault(context, { key, defaultValue })kv.has(context, { key })kv.delete(context, { key })
Expired keys are treated as missing and cleaned up lazily on read.
An example app can be found in the demo package.