Skip to content
sproutboatDocs
Esc
↑↓navigate↵open⌘Jpreview
On this page

KV

A key-value store bound to env.NAME.

Configuration

"kv_namespaces": ["SESSIONS"]

Bare names are auto-provisioned on deploy; see Storage resources.

Usage

export default {
  async fetch(request, env, ctx) {
    await env.SESSIONS.put("k", "v");
    await env.SESSIONS.put("session:abc", "token", { expirationTtl: 3600 });

    const value = await env.SESSIONS.get("k"); // "v", or null
    const profile = await env.SESSIONS.get<{ name: string }>("user:1", "json");

    const { keys } = await env.SESSIONS.list({ prefix: "session:" });
    // keys: [{ name: "session:abc", expiration: 1794503103 }]

    await env.SESSIONS.delete("k");
    return Response.json({ value, profile, keys: keys.map((key) => key.name) });
  },
} satisfies ExportedHandler<Env>;

This is the Cloudflare Workers KV API, so the same code runs on Workers. From compatibility date 2026-10-25 every call returns a Promise. Before it they are synchronous, and the older, smaller API applies (see below). await works at both dates, so write it.

Methods

Method Signature Returns
put (key, value, { expirationTtl?, expiration?, metadata? }) Promise<void>. value is a string, an ArrayBuffer, a typed array or a ReadableStream.
get (key, type?) Promise<string | null>. type is "text" (the default), "json", "arrayBuffer" or "stream".
getWithMetadata (key, type?) Promise<{ value, metadata, cacheStatus }>
delete (key) Promise<void>
list ({ prefix?, limit?, cursor? }) Promise<{ keys, list_complete, cursor? }>. Each key is { name, expiration?, metadata? }; a page holds up to 1000 keys. Pass the returned cursor to read the next page.

expirationTtl is seconds from now, at least 60. expiration is an absolute time in Unix seconds. An expired key reads as null and is left out of list. A list prefix matches exactly: case matters, and _ and % are not wildcards.

Before compatibility date 2026-10-25

Calls return their value directly, and list takes a prefix string and returns the key names:

const names = env.SESSIONS.list("session:"); // string[], sorted

Move compatibility_date to 2026-10-25 or later for the Workers API above.

Was this page helpful?