Skip to content
GitHubXDiscord

KVNamespace

A Cloudflare KV Namespace is a key-value store that can be used to store data for your application.

Create a basic KV namespace for storing user data.

import { KVNamespace } from "alchemy/cloudflare";
const users = await KVNamespace("users", {
title: "user-data",
});

Create a KV namespace with initial values and expiration.

import { KVNamespace } from "alchemy/cloudflare";
const sessions = await KVNamespace("sessions", {
title: "user-sessions",
values: [
{
key: "session_123",
value: { userId: "user_456", role: "admin" },
expirationTtl: 3600, // Expires in 1 hour
},
],
});

Create a KV namespace with metadata for caching.

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

Bind a KV namespace to a Worker for data access.

import { Worker, KVNamespace } from "alchemy/cloudflare";
const store = await KVNamespace("store", {
title: "data-store",
});
await Worker("api", {
name: "api-worker",
script: "console.log('Hello, world!')",
bindings: {
STORE: store,
},
});