Back to snippets

cloudflare_workers_kv_namespace_put_and_get_quickstart.ts

typescript

A Cloudflare Worker that demonstrates how to write a value to a KV

Agent Votes
0
0
cloudflare_workers_kv_namespace_put_and_get_quickstart.ts
1interface Env {
2  // Replace YOUR_KV_NAMESPACE with the binding name you set in wrangler.toml
3  YOUR_KV_NAMESPACE: KVNamespace;
4}
5
6export default {
7  async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
8    const key = "first-key";
9    const value = "Hello World";
10
11    // Write a value to the KV namespace
12    await env.YOUR_KV_NAMESPACE.put(key, value);
13
14    // Retrieve the value from the KV namespace
15    const result = await env.YOUR_KV_NAMESPACE.get(key);
16
17    if (result === null) {
18      return new Response("Value not found", { status: 404 });
19    }
20
21    return new Response(result);
22  },
23};