Skip to content

Commit fa80de7

Browse files
Oxyjunharshil1712RebeccaTamachiro
authored
[Workers KV] Improving KV getting started guide (#22573)
* Improving KV getting started guide * minor updates * Adding one sentence. * Apply suggestions from code review Co-authored-by: Rebecca Tamachiro <[email protected]> * Implementing feedback --------- Co-authored-by: Harshil Agrawal <[email protected]> Co-authored-by: Rebecca Tamachiro <[email protected]>
1 parent b17b8d1 commit fa80de7

File tree

1 file changed

+101
-116
lines changed

1 file changed

+101
-116
lines changed

src/content/docs/kv/get-started.mdx

Lines changed: 101 additions & 116 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
---
22
title: Getting started
33
pcx_content_type: get-started
4+
summary: |
5+
Create a basic key-value store which stores the notification configuration of all users in an application, where each user may have `enabled` or `disabled` notifications.
6+
updated: 2025-05-19
47
sidebar:
58
order: 2
69
---
710

8-
import { Render, PackageManagers, Steps, FileTree, Details, Tabs, TabItem, WranglerConfig } from "~/components";
11+
import { Render, PackageManagers, Steps, FileTree, Details, Tabs, TabItem, WranglerConfig, GitHubCode } from "~/components";
912

1013
Workers KV provides low-latency, high-throughput global storage to your [Cloudflare Workers](/workers/) applications. Workers KV is ideal for storing user configuration data, routing data, A/B testing configurations and authentication tokens, and is well suited for read-heavy workloads.
1114

@@ -15,7 +18,17 @@ This guide instructs you through:
1518
- Writing key-value pairs to your KV namespace from a Cloudflare Worker.
1619
- Reading key-value pairs from a KV namespace.
1720

18-
You can perform these tasks through the CLI or through the Cloudflare dashboard.
21+
You can perform these tasks through the Wrangler CLI or through the Cloudflare dashboard.
22+
23+
## Quick start
24+
25+
If you want to skip the setup steps and get started quickly, click on the button below.
26+
27+
[![Deploy to Cloudflare](https://deploy.workers.cloudflare.com/button)](https://deploy.workers.cloudflare.com/?url=https://github.com/cloudflare/docs-examples/tree/update/kv/kv/kv-get-started)
28+
29+
This creates a repository in your GitHub account and deploys the application to Cloudflare Workers. Use this option if you are familiar with Cloudflare Workers, and wish to skip the step-by-step guidance.
30+
31+
You may wish to manually follow the steps if you are new to Cloudflare Workers.
1932

2033
## Prerequisites
2134

@@ -99,11 +112,11 @@ Create a new Worker to read and write to your KV namespace.
99112

100113
## 2. Create a KV namespace
101114

102-
A [KV namespace](/kv/concepts/kv-namespaces/) is a key-value database replicated to Cloudflares global network.
115+
A [KV namespace](/kv/concepts/kv-namespaces/) is a key-value database replicated to Cloudflare's global network.
103116

104117
<Tabs syncKey = 'CLIvsDash'> <TabItem label='CLI'>
105118

106-
[Wrangler](/workers/wrangler/) allows you to put, list, get, and delete entries within your KV namespace.
119+
You can use [Wrangler](/workers/wrangler/) to create a new KV namespace. You can also use it to perform operations such as put, list, get, and delete within your KV namespace.
107120

108121
:::note
109122

@@ -119,21 +132,26 @@ To create a KV namespace via Wrangler:
119132
npx wrangler kv namespace create <BINDING_NAME>
120133
```
121134

122-
The `npx wrangler kv namespace create <BINDING_NAME>` subcommand takes a new binding name as its argument. A KV namespace is created using a concatenation of your Workers name (from your Wrangler file) and the binding name you provide. A `BINDING_ID` is randomly generated for you.
135+
The `npx wrangler kv namespace create <BINDING_NAME>` subcommand takes a new binding name as its argument. A KV namespace is created using a concatenation of your Worker's name (from your Wrangler file) and the binding name you provide. A `<BINDING_ID>` is randomly generated for you.
123136

124-
For this tutorial, use the binding name `BINDING_NAME`.
137+
For this tutorial, use the binding name `USERS_NOTIFICATION_CONFIG`.
125138

126-
```sh
127-
npx wrangler kv namespace create BINDING_NAME
139+
```sh ins="USERS_NOTIFICATION_CONFIG"
140+
npx wrangler kv namespace create USERS_NOTIFICATION_CONFIG
128141
```
129142

130143
```sh output
131-
🌀 Creating namespace with title kv-tutorial-BINDING_NAME
132-
✨ Success!
133-
Add the following to your configuration file:
134-
[[kv_namespaces]]
135-
binding = "BINDING_NAME"
136-
id = "<BINDING_ID>"
144+
🌀 Creating namespace with title "USERS_NOTIFICATION_CONFIG"
145+
✨ Success!
146+
Add the following to your configuration file in your kv_namespaces array:
147+
{
148+
"kv_namespaces": [
149+
{
150+
"binding": "USERS_NOTIFICATION_CONFIG",
151+
"id": "<BINDING_ID>"
152+
}
153+
]
154+
}
137155
```
138156

139157
</Steps>
@@ -153,6 +171,14 @@ To create a KV namespace via Wrangler:
153171

154172
You must create a binding to connect your Worker with your KV namespace. [Bindings](/workers/runtime-apis/bindings/) allow your Workers to access resources, like KV, on the Cloudflare developer platform.
155173

174+
:::note[Bindings]
175+
176+
A binding is how your Worker interacts with external resources such as [KV namespaces](/kv/concepts/kv-namespaces/). A binding is a runtime variable that the Workers runtime provides to your code. You can declare a variable name in your Wrangler file that binds to these resources at runtime, and interact with them through this variable. Every binding's variable name and behavior is determined by you when deploying the Worker.
177+
178+
Refer to [Environment](/kv/reference/environments/) for more information.
179+
180+
:::
181+
156182
To bind your KV namespace to your Worker:
157183

158184
<Tabs syncKey='CLIvsDash'><TabItem label='CLI'>
@@ -163,27 +189,19 @@ To bind your KV namespace to your Worker:
163189

164190
```toml
165191
[[kv_namespaces]]
166-
binding = "<BINDING_NAME>"
192+
binding = "USERS_NOTIFICATION_CONFIG"
167193
id = "<BINDING_ID>"
168194
```
169195

170196
</WranglerConfig>
171197

172198
Binding names do not need to correspond to the namespace you created. Binding names are only a reference. Specifically:
173199

174-
- The value (string) you set for `<BINDING_NAME>` is used to reference this KV namespace in your Worker. For this tutorial, this should be `BINDING_NAME`.
200+
- The value (string) you set for `binding` is used to reference this KV namespace in your Worker. For this tutorial, this should be `USERS_NOTIFICATION_CONFIG`.
175201
- The binding must be [a valid JavaScript variable name](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#variables). For example, `binding = "MY_KV"` or `binding = "routingConfig"` would both be valid names for the binding.
176-
- Your binding is available in your Worker at `env.<BINDING_NAME>` from within your Worker.
202+
- Your binding is available in your Worker at `env.<BINDING_NAME>` from within your Worker. For this tutorial, the binding is available at `env.USERS_NOTIFICATION_CONFIG`.
177203
</Steps>
178204

179-
:::note[Bindings]
180-
181-
A binding is how your Worker interacts with external resources such as [KV namespaces](/kv/concepts/kv-namespaces/). A binding is a runtime variable that the Workers runtime provides to your code. You can declare a variable name in your Wrangler file that binds to these resources at runtime, and interact with them through this variable. Every binding's variable name and behavior is determined by you when deploying the Worker.
182-
183-
Refer to [Environment](/kv/reference/environments/) for more information.
184-
185-
:::
186-
187205
</TabItem><TabItem label='Dashboard'>
188206

189207
<Steps>
@@ -201,7 +219,7 @@ Refer to [Environment](/kv/reference/environments/) for more information.
201219

202220
You can interact with your KV namespace via [Wrangler](/workers/wrangler/install-and-update/) or directly from your [Workers](/workers/) application.
203221

204-
### Write a value
222+
### 4.1. Write a value
205223

206224
<Tabs syncKey='CLIvsDash'><TabItem label = 'CLI'>
207225

@@ -214,27 +232,38 @@ To write a value to your empty KV namespace using Wrangler:
214232
npx wrangler kv key put --binding=<BINDING_NAME> "<KEY>" "<VALUE>"
215233
```
216234

235+
In this tutorial, you will add a key `user_1` with value `enabled` to the KV namespace you created in [step 2](/kv/get-started/#2-create-a-kv-namespace).
236+
237+
```sh
238+
npx wrangler kv key put --binding=USERS_NOTIFICATION_CONFIG "user_1" "enabled"
239+
```
217240
```sh output
218-
Writing the value "<VALUE>" to key "<KEY>" on namespace <BINDING_ID>.
241+
Writing the value "enabled" to key "user_1" on namespace <BINDING_ID>.
219242
```
220243
</Steps>
221244

245+
:::note[Using `--namespace-id`]
222246
Instead of using `--binding`, you can also use `--namespace-id` to specify which KV namespace should receive the operation:
223247

224-
```sh
248+
```sh "--namespace-id=<BINDING_ID>"
225249
npx wrangler kv key put --namespace-id=<BINDING_ID> "<KEY>" "<VALUE>"
226250
```
227251

228252
```sh output
229253
Writing the value "<VALUE>" to key "<KEY>" on namespace <BINDING_ID>.
230254
```
255+
:::
231256

232-
To create a key and a value in local mode, add the `--local` flag at the end of the command:
257+
:::note[Storing values in remote KV namespace]
233258

234-
```sh
235-
npx wrangler kv key put --namespace-id=xxxxxxxxxxxxxxxx "<KEY>" "<VALUE>" --local
259+
By default, the values are written locally. To create a key and a value in your remote KV namespace, add the `--remote` flag at the end of the command:
260+
261+
```sh ins="--remote"
262+
npx wrangler kv key put --namespace-id=xxxxxxxxxxxxxxxx "<KEY>" "<VALUE>" --remote
236263
```
237264

265+
:::
266+
238267
</TabItem><TabItem label = 'Dashboard'>
239268
<Steps>
240269
1. Go to [**Storage & Databases** > **KV**](https://dash.cloudflare.com/?to=/:account/workers/kv/namespaces).
@@ -247,50 +276,38 @@ npx wrangler kv key put --namespace-id=xxxxxxxxxxxxxxxx "<KEY>" "<VALUE>" --loca
247276

248277
</TabItem> </Tabs>
249278

250-
### Get a value
279+
### 4.2. Get a value
251280

252281
<Tabs syncKey='CLIvsDash'><TabItem label = 'CLI'>
253282

254-
To access the value using Wrangler:
283+
To access the value from your KV namespace using Wrangler:
255284

256285
<Steps>
257286
1. Run the `wrangler kv key get` subcommand in your terminal, and input your key value:
258287

259288
```sh
260-
# Replace [OPTIONS] with --binding or --namespace-id
261-
npx wrangler kv key get [OPTIONS] "<KEY>"
289+
npx wrangler kv key get --binding=<BINDING_NAME> "<KEY>"
262290
```
263291

264-
A KV namespace can be specified in two ways:
265-
266-
<Details header="With a `--binding`">
267-
268-
```sh
269-
npx wrangler kv key get --binding=<BINDING_NAME> "<KEY>"
270-
```
292+
In this tutorial, you will get the value of the key `user_1` from the KV namespace you created in [step 2](/kv/get-started/#2-create-a-kv-namespace).
271293

272-
</Details>
273-
274-
<Details header ="With a `--namespace-id`">
294+
:::note
295+
To view the value directly within the terminal, you use the `--text` flag.
296+
:::
275297

276298
```sh
277-
npx wrangler kv key get --namespace-id=<YOUR_ID> "<KEY>"
299+
npx wrangler kv key get --binding=USERS_NOTIFICATION_CONFIG "user_1" --text
278300
```
279-
</Details>
280301

281-
</Steps>
302+
Similar to the `put` command, the `get` command can also be used to access a KV namespace in two ways - with `--binding` or `--namespace-id`:
282303

283-
You can add a `--preview` flag to interact with a preview namespace instead of a production namespace.
304+
</Steps>
284305

285306
:::caution
286307

287308
Exactly **one** of `--binding` or `--namespace-id` is required.
288309
:::
289310

290-
:::note
291-
To view the value directly within the terminal, add `--text`
292-
:::
293-
294311
Refer to the [`kv bulk` documentation](/kv/reference/kv-commands/#kv-bulk) to write a file of multiple key-value pairs to a given KV namespace.
295312

296313
</TabItem><TabItem label='Dashboard'>
@@ -316,69 +333,46 @@ To have `wrangler dev` connect to your Workers KV namespace running on Cloudflar
316333
:::
317334

318335
<Steps>
319-
1. In your Worker script, add your KV binding in the `Env` interface:
336+
1. In your Worker script, add your KV binding in the `Env` interface. If you have bootstrapped your project with JavaScript, this step is not required.
320337

321338
```ts
322339
interface Env {
323-
BINDING_NAME: KVNamespace;
340+
USERS_NOTIFICATION_CONFIG: KVNamespace;
324341
// ... other binding types
325342
}
326343
```
327344

328-
2. Use the `put()` method on `BINDING_NAME` to create a new key-value pair, or to update the value for a particular key:
345+
2. Use the `put()` method on `USERS_NOTIFICATION_CONFIG` to create a new key-value pair. You will add a new key `user_2` with value `disabled` to your KV namespace.
329346

330347
```ts
331-
let value = await env.BINDING_NAME.put(key, value);
348+
let value = await env.USERS_NOTIFICATION_CONFIG.put("user_2", "disabled");
332349
```
333350

334-
3. Use the KV `get()` method to fetch the data you stored in your KV database:
351+
3. Use the KV `get()` method to fetch the data you stored in your KV namespace. You will fetch the value of the key `user_2` from your KV namespace.
335352

336353
```ts
337-
let value = await env.BINDING_NAME.get("KEY");
354+
let value = await env.USERS_NOTIFICATION_CONFIG.get("user_2");
338355
```
339356
</Steps>
340357

341358
Your Worker code should look like this:
342359

343-
```ts
344-
export interface Env {
345-
BINDING_NAME: KVNamespace;
346-
}
347-
348-
export default {
349-
async fetch(request, env, ctx): Promise<Response> {
350-
try {
351-
await env.BINDING_NAME.put("KEY", "VALUE");
352-
const value = await env.BINDING_NAME.get("KEY");
353-
if (value === null) {
354-
return new Response("Value not found", { status: 404 });
355-
}
356-
return new Response(value);
357-
} catch (err) {
358-
// In a production application, you could instead choose to retry your KV
359-
// read or fall back to a default code path.
360-
console.error(`KV returned error: ${err}`);
361-
return new Response(err, { status: 500 });
362-
}
363-
},
364-
} satisfies ExportedHandler<Env>;
365-
```
360+
<GitHubCode
361+
repo="cloudflare/docs-examples"
362+
file="kv/kv-get-started/src/index.ts"
363+
commit="831724c421748229864c1ea28c854e352c62625e"
364+
lang="ts"
365+
lines="1-26"
366+
useTypeScriptExample={true}
367+
/>
366368

367369
The code above:
368370

369-
1. Writes a key to `BINDING_NAME` using KV's `put()` method.
370-
2. Reads the same key using KV's `get()` method, and returns an error if the key is null (or in case the key is not set, or does not exist).
371-
3. Uses JavaScript's [`try...catch`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch) exception handling to catch potential errors. When writing or reading from any service, such as Workers KV or external APIs using `fetch()`, you should expect to handle exceptions explicitly.
372-
373-
To run your project locally, enter the following command within your project directory:
374-
375-
```sh
376-
npx wrangler dev
377-
```
378-
379-
When you run `wrangler dev`, Wrangler provides a URL (usually a `localhost:8787`) to review your Worker. The browser prints your value when you visit the URL provided by Wrangler.
380-
381-
The browser should simply return the `VALUE` corresponding to the `KEY` you have specified with the `get()` method.
371+
1. Writes a key to your KV namespace using KV's `put()` method.
372+
2. Reads the same key using KV's `get()` method.
373+
3. Checks if the key is null, and returns a `404` response if it is.
374+
4. If the key is not null, it returns the value of the key.
375+
5. Uses JavaScript's [`try...catch`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/try...catch) exception handling to catch potential errors. When writing or reading from any service, such as Workers KV or external APIs using `fetch()`, you should expect to handle exceptions explicitly.
382376

383377
</TabItem><TabItem label = 'Dashboard'>
384378

@@ -388,25 +382,14 @@ The browser should simply return the `VALUE` corresponding to the `KEY` you have
388382
3. Select **Edit Code**.
389383
4. Clear the contents of the `workers.js` file, then paste the following code.
390384

391-
```js
392-
export default {
393-
async fetch(request, env, ctx) {
394-
try {
395-
await env.BINDING_NAME.put("KEY", "VALUE");
396-
const value = await env.BINDING_NAME.get("KEY");
397-
if (value === null) {
398-
return new Response("Value not found", { status: 404 });
399-
}
400-
return new Response(value);
401-
} catch (err) {
402-
// In a production application, you could instead choose to retry your KV
403-
// read or fall back to a default code path.
404-
console.error(`KV returned error: ${err}`);
405-
return new Response(err.toString(), { status: 500 });
406-
}
407-
},
408-
};
409-
```
385+
<GitHubCode
386+
repo="cloudflare/docs-examples"
387+
file="kv/kv-get-started/src/index.ts"
388+
commit="831724c421748229864c1ea28c854e352c62625e"
389+
lang="ts"
390+
lines="1-26"
391+
useTypeScriptExample={true}
392+
/>
410393

411394
The code above:
412395

@@ -421,15 +404,17 @@ The browser should simply return the `VALUE` corresponding to the `KEY` you have
421404

422405
</TabItem></Tabs>
423406

424-
## 6. Deploy your KV
407+
## 6. Deploy your Worker
408+
409+
Deploy your Worker to Cloudflare's global network.
425410

426411
<Tabs syncKey = 'CLIvsDash'><TabItem label = 'CLI'>
427412

428413
<Steps>
429414
1. Run the following command to deploy KV to Cloudflare's global network:
430415

431416
```sh
432-
npx wrangler deploy
417+
npm run deploy
433418
```
434419

435420
2. Visit the URL for your newly created Workers KV application.

0 commit comments

Comments
 (0)