Skip to main content

KVNamespace

A Cloudflare KV Namespace is a key-value store for storing data in your Worker applications.

Props

title
string
Title of the namespace.
values
KVPair[]
KV pairs to store in the namespace (only used for initial setup or updates).
adopt
boolean
default:"false"
Whether to adopt an existing namespace with the same title if it exists.
delete
boolean
default:"true"
Whether to delete the namespace when the resource is removed from Alchemy.

Output

namespaceId
string
The ID of the namespace.
title
string
Title of the namespace.
createdAt
number
Time at which the namespace was created.
modifiedAt
number
Time at which the namespace was last modified.
type
kv_namespace
Type identifier for the binding.

Examples

Basic KV Namespace

const users = await KVNamespace("users", {
  title: "user-data"
});

const worker = await Worker("api", {
  entrypoint: "./src/worker.ts",
  bindings: {
    USERS: users
  }
});

KV Namespace with Initial Values

const sessions = await KVNamespace("sessions", {
  title: "user-sessions",
  values: [{
    key: "session_123",
    value: { userId: "user_456", role: "admin" },
    expirationTtl: 3600
  }]
});

KV Namespace with Metadata

const assets = await KVNamespace("assets", {
  title: "static-assets",
  values: [{
    key: "main.js",
    value: "content...",
    metadata: {
      contentType: "application/javascript",
      etag: "abc123"
    }
  }]
});

Adopt Existing Namespace

const existingNamespace = await KVNamespace("existing-ns", {
  title: "existing-namespace",
  adopt: true,
  values: [{
    key: "config",
    value: { setting: "updated-value" }
  }]
});

Build docs developers (and LLMs) love