Skip to content

Commit cecf711

Browse files
committed
Improving KV getting started guide
1 parent f9903c2 commit cecf711

File tree

1 file changed

+99
-81
lines changed

1 file changed

+99
-81
lines changed

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

Lines changed: 99 additions & 81 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,7 +112,7 @@ 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

@@ -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>
@@ -163,17 +181,17 @@ To bind your KV namespace to your Worker:
163181

164182
```toml
165183
[[kv_namespaces]]
166-
binding = "<BINDING_NAME>"
184+
binding = "USERS_NOTIFICATION_CONFIG"
167185
id = "<BINDING_ID>"
168186
```
169187

170188
</WranglerConfig>
171189

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

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`.
192+
- 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`.
175193
- 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.
194+
- 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`.
177195
</Steps>
178196

179197
:::note[Bindings]
@@ -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,24 +232,29 @@ 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+
```sh
236+
npx wrangler kv key put --binding=USERS_NOTIFICATION_CONFIG "user_1" "enabled"
237+
```
217238
```sh output
218-
Writing the value "<VALUE>" to key "<KEY>" on namespace <BINDING_ID>.
239+
Writing the value "enabled" to key "user_1" on namespace <BINDING_ID>.
219240
```
220241
</Steps>
221242

243+
:::note
222244
Instead of using `--binding`, you can also use `--namespace-id` to specify which KV namespace should receive the operation:
223245

224-
```sh
246+
```sh "--namespace-id=<BINDING_ID>"
225247
npx wrangler kv key put --namespace-id=<BINDING_ID> "<KEY>" "<VALUE>"
226248
```
227249

228250
```sh output
229251
Writing the value "<VALUE>" to key "<KEY>" on namespace <BINDING_ID>.
230252
```
253+
:::
231254

232255
To create a key and a value in local mode, add the `--local` flag at the end of the command:
233256

234-
```sh
257+
```sh ins="--local"
235258
npx wrangler kv key put --namespace-id=xxxxxxxxxxxxxxxx "<KEY>" "<VALUE>" --local
236259
```
237260

@@ -247,7 +270,7 @@ npx wrangler kv key put --namespace-id=xxxxxxxxxxxxxxxx "<KEY>" "<VALUE>" --loca
247270

248271
</TabItem> </Tabs>
249272

250-
### Get a value
273+
### 4.2. Get a value
251274

252275
<Tabs syncKey='CLIvsDash'><TabItem label = 'CLI'>
253276

@@ -261,7 +284,7 @@ To access the value using Wrangler:
261284
npx wrangler kv key get [OPTIONS] "<KEY>"
262285
```
263286

264-
A KV namespace can be specified in two ways:
287+
A KV namespace can be specified in two ways. Replace `[OPTIONS]` with `--binding` or `--namespace-id`:
265288

266289
<Details header="With a `--binding`">
267290

@@ -278,9 +301,15 @@ To access the value using Wrangler:
278301
```
279302
</Details>
280303

304+
For example, using the `--binding` option:
305+
306+
```sh
307+
npx wrangler kv key get --binding=USERS_NOTIFICATION_CONFIG "user_1"
308+
```
309+
281310
</Steps>
282311

283-
You can add a `--preview` flag to interact with a preview namespace instead of a production namespace.
312+
{/* You can add a `--preview` flag to interact with a preview namespace instead of a production namespace. */}
284313

285314
:::caution
286315

@@ -320,66 +349,41 @@ To have `wrangler dev` connect to your Workers KV namespace running on Cloudflar
320349

321350
```ts
322351
interface Env {
323-
BINDING_NAME: KVNamespace;
352+
USERS_NOTIFICATION_CONFIG: KVNamespace;
324353
// ... other binding types
325354
}
326355
```
327356

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:
357+
2. Use the `put()` method on `USERS_NOTIFICATION_CONFIG` to create a new key-value pair:
329358

330359
```ts
331-
let value = await env.BINDING_NAME.put(key, value);
360+
let value = await env.USERS_NOTIFICATION_CONFIG.put(key, value);
332361
```
333362

334363
3. Use the KV `get()` method to fetch the data you stored in your KV database:
335364

336365
```ts
337-
let value = await env.BINDING_NAME.get("KEY");
366+
let value = await env.USERS_NOTIFICATION_CONFIG.get("KEY");
338367
```
339368
</Steps>
340369

341370
Your Worker code should look like this:
342371

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-
```
372+
<GitHubCode
373+
repo="cloudflare/docs-examples"
374+
file="kv/kv-get-started/src/index.ts"
375+
commit="831724c421748229864c1ea28c854e352c62625e"
376+
lang="ts"
377+
lines="1-26"
378+
useTypeScriptExample={true}
379+
/>
366380

367381
The code above:
368382

369-
1. Writes a key to `BINDING_NAME` using KV's `put()` method.
383+
1. Writes a key to `USERS_NOTIFICATION_CONFIG` binding using KV's `put()` method.
370384
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).
371385
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.
372386

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.
382-
383387
</TabItem><TabItem label = 'Dashboard'>
384388

385389
<Steps>
@@ -388,25 +392,14 @@ The browser should simply return the `VALUE` corresponding to the `KEY` you have
388392
3. Select **Edit Code**.
389393
4. Clear the contents of the `workers.js` file, then paste the following code.
390394

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-
```
395+
<GitHubCode
396+
repo="cloudflare/docs-examples"
397+
file="kv/kv-get-started/src/index.ts"
398+
commit="831724c421748229864c1ea28c854e352c62625e"
399+
lang="ts"
400+
lines="1-26"
401+
useTypeScriptExample={true}
402+
/>
410403

411404
The code above:
412405

@@ -423,13 +416,38 @@ The browser should simply return the `VALUE` corresponding to the `KEY` you have
423416

424417
## 6. Deploy your KV
425418

419+
You can deploy your project in one of two ways:
420+
421+
- **Locally:** Runs from your machine on a local server. The URL to your web application is only accessible while you are running the application from your terminal.
422+
- **Remotely:** Runs on Cloudflare's global network. The URL to your web application will be accessible to anyone with the URL.
423+
424+
:::note
425+
You can only deploy your project locally through the Wrangler CLI. You can only deploy remotely when deploying through the Cloudflare dashboard.
426+
:::
427+
428+
In this tutorial, we expect the URL to simply return the value `disabled` (which corresponds to the key `user_2`).
429+
430+
### Deploy your project locally
431+
432+
<Steps>
433+
1. Run the following command within your project directory:
434+
435+
```sh
436+
npm run dev
437+
```
438+
439+
2. Visit the URL for your newly created Workers KV application running on your local machine, as provided by Wrangler (usually `localhost:8787`).
440+
</Steps>
441+
442+
### Deploy your project globally
443+
426444
<Tabs syncKey = 'CLIvsDash'><TabItem label = 'CLI'>
427445

428446
<Steps>
429447
1. Run the following command to deploy KV to Cloudflare's global network:
430448

431449
```sh
432-
npx wrangler deploy
450+
npm run deploy
433451
```
434452

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

0 commit comments

Comments
 (0)