Skip to content

Store data with deploybase KV

deploybase KV is a key-value store for your functions and your server-rendered app. Data is stored in Paris, in Scaleway object storage replicated across several availability zones. A function reads and writes it through @deploybase/kv, with no keys or addresses to configure: the platform gives every function of a team with KV its own token.

KV is in beta. It is included in the Starter, Pro and Scale plans, with no price per request, and each team can store 1 GB while the beta lasts. Limits per plan are set when the beta ends. The Free plan does not include it. Every method, limit and error code is in the KV reference.

Use KV when you look a value up by its key: sessions, counters, feature flags, cached API answers, a small document per user. Use a SQL database when you need to search across records, join them or change several in one transaction; Connect a database sets one up.

In your project:

Terminal window
npm install @deploybase/kv

Your build installs it and every function that imports it gets it bundled in. It needs no configuration:

functions/hello.js
import { kv } from "@deploybase/kv";
export default async function handler(request) {
await kv.set("greeting", { text: "Hello from Paris" });
return Response.json(await kv.get("greeting"));
}

kv works only in a deployed function. Anywhere else, in the build step included, it throws a KVError with code KV_NOT_AVAILABLE. To run your code on your own machine or in a test, use the in-memory client.

A function that was already running when your team got KV gets access within about 10 minutes, without a deploy. A production deploy gives it access at once.

Give a key a ttl in seconds, at least 60, and it disappears on its own. This function signs a visitor in for a day, reads the session back and signs them out:

functions/session.js
import { kv } from "@deploybase/kv";
const sessions = kv.store("sessions");
const DAY = 24 * 60 * 60;
const cors = {
"access-control-allow-origin": "https://www.example.com",
"access-control-allow-headers": "authorization",
"access-control-allow-methods": "GET, POST, DELETE",
};
export default async function handler(request) {
if (request.method === "OPTIONS") return new Response(null, { status: 204, headers: cors });
if (request.method === "POST") {
// Check the visitor's password or sign-in link here first.
const token = crypto.randomUUID();
await sessions.set(token, { userId: "user-0001" }, { ttl: DAY });
return Response.json({ token, expiresIn: DAY }, { headers: cors });
}
const token = request.headers.get("authorization")?.replace(/^Bearer /, "");
if (!token) return new Response("Not signed in", { status: 401, headers: cors });
if (request.method === "DELETE") {
await sessions.delete(token);
return new Response(null, { status: 204, headers: cors });
}
const session = await sessions.get(token);
if (!session) return new Response("Not signed in", { status: 401, headers: cors });
return Response.json(session, { headers: cors });
}

kv.store("sessions") is a named store with the same methods as kv, so session keys never mix with your other keys. get returns null once the key has expired.

The function answers at its own hostname, https://session-{subdomain}.fn.deploybase.eu, not on your site’s domain. A cookie it set would belong to that hostname, and browsers treat it as a third-party cookie and often block it. So the page keeps the token it gets from the POST, for example in sessionStorage, and sends it as Authorization: Bearer <token> on later calls. Set access-control-allow-origin to your site’s address. If you want a session cookie on your own domain, use a server-rendered app: it answers on your site’s domain and can set the cookie there.

Two requests that read a counter at the same moment and both write count + 1 lose one of the two. Write only if the key is still at the version you read, and read again when it is not:

functions/_lib/counter.js
const pause = () => new Promise((resolve) => setTimeout(resolve, 20 + Math.random() * 80));
export async function increment(store, key) {
for (let attempt = 0; attempt < 5; attempt++) {
if (attempt > 0) await pause(); // spread out requests that collided
const entry = await store.getWithMetadata(key);
if (entry === null) {
const created = await store.set(key, 1, { onlyIfNew: true });
if (created.modified) return 1;
continue; // another request created it first
}
const next = entry.value + 1;
const updated = await store.set(key, next, { onlyIfVersion: entry.version });
if (updated.modified) return next;
// another request wrote in between: read again
}
throw new Error(`Too many writes to ${key} at once`);
}
functions/visits.js
import { kv } from "@deploybase/kv";
import { increment } from "./_lib/counter.js";
export default async function handler() {
return Response.json({ visits: await increment(kv, "visits") });
}

A write whose condition does not hold is not an error: it returns { modified: false }. If increment still gives up after five tries, the key is very busy: show the visitor the last count you have, or answer 503 and let the page try again a moment later. Files in a subdirectory of functions/, such as _lib/, are shared code and are bundled into the functions that import them.

Production and previews never see each other’s data:

  • Production: your functions and the production deployment of a server-rendered app.
  • Preview: server-rendered branch previews. All previews of a project share one preview data set, so two branches write to the same keys.

The code is the same in both; the token the platform gives each deployment decides which data it reaches. Functions in functions/ run on production deploys only, so they always use production data and have no preview. To try a change to a function without touching production data, run it against the memory store. A server-rendered app’s branch previews use the preview data set.

@deploybase/kv/memory is the same client with its data in memory: the same methods, options, conditions, expiry, validation and size limits, and an empty store each time you create one. Write your code to take the store as a parameter, as increment above does, and hand it a memory store in a test:

test/counter.test.js
import { test } from "node:test";
import assert from "node:assert/strict";
import { createMemoryClient } from "@deploybase/kv/memory";
import { increment } from "../functions/_lib/counter.js";
test("counts visits", async () => {
const store = createMemoryClient();
assert.equal(await increment(store, "visits"), 1);
assert.equal(await increment(store, "visits"), 2);
});

Run it with node --test. To expire keys without waiting, pass your own clock in milliseconds: createMemoryClient({ now: () => fakeNow }).

To run your app on your own machine, choose the memory store with a variable you set only there:

import { kv } from "@deploybase/kv";
import { createMemoryClient } from "@deploybase/kv/memory";
export const store = process.env.USE_MEMORY_KV === "1" ? createMemoryClient() : kv;

Do not fall back to the memory store when kv is not available. In a deployed function that would accept every write and keep none of them.

The memory store holds its data as long as the process runs. What differs from the real service: it has no rate limit and no 1 GB team limit, so it never throws KV_RATE_LIMITED or KV_STORAGE_LIMIT_EXCEEDED; it never times out or loses the network; and an expired key leaves list at once.

Open the project and choose KV store in the sidebar. It lists each store’s keys for Production and Preview, shows a key’s value and who last wrote it, and lets anyone with the Member role or above edit or delete one. The MCP server has the same reads and writes for agents.

  • A deleted or overwritten value cannot be restored. KV keeps no backups and no earlier versions. The storage is replicated across availability zones, which protects against a failed disk or zone, not against your own delete.
  • Plan for KV being briefly unavailable. The client retries short outages itself. When it still fails, it throws a KVError; answer with a 503 or a fallback rather than letting the request crash. The reference lists every error and what to do after a write that timed out.
  • Deleting the project deletes its KV data, in both environments.
  • The 1 GB limit counts your whole team, every project and both environments. Over it, writes fail with KV_STORAGE_LIMIT_EXCEEDED until you delete keys.

The reference has every limit and the known edges.

Live 582ac705 built