KVNamespace
A Cloudflare KV Namespace is a key-value store for storing data in your Worker applications.
Props
Title of the namespace.
${app}-${stage}-${id}
KV pairs to store in the namespace (only used for initial setup or updates).
Value to store (string or JSON object).
Optional expiration in seconds from now.
Optional expiration timestamp in seconds since epoch.
Optional metadata for the key.
Whether to adopt an existing namespace with the same title if it exists.
Whether to delete the namespace when the resource is removed from Alchemy.
Output
Time at which the namespace was created.
Time at which the namespace was last modified.
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
}]
});
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" }
}]
});