You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/content/docs/kv/get-started.mdx
+99-81Lines changed: 99 additions & 81 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,11 +1,14 @@
1
1
---
2
2
title: Getting started
3
3
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.
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.
11
14
@@ -15,7 +18,17 @@ This guide instructs you through:
15
18
- Writing key-value pairs to your KV namespace from a Cloudflare Worker.
16
19
- Reading key-value pairs from a KV namespace.
17
20
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
+
[](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.
19
32
20
33
## Prerequisites
21
34
@@ -99,7 +112,7 @@ Create a new Worker to read and write to your KV namespace.
99
112
100
113
## 2. Create a KV namespace
101
114
102
-
A [KV namespace](/kv/concepts/kv-namespaces/) is a key-value database replicated to Cloudflare’s global network.
115
+
A [KV namespace](/kv/concepts/kv-namespaces/) is a key-value database replicated to Cloudflare's global network.
103
116
104
117
<TabssyncKey='CLIvsDash'> <TabItemlabel='CLI'>
105
118
@@ -119,21 +132,26 @@ To create a KV namespace via Wrangler:
119
132
npx wrangler kv namespace create <BINDING_NAME>
120
133
```
121
134
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 Worker’s 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.
123
136
124
-
For this tutorial, use the binding name `BINDING_NAME`.
137
+
For this tutorial, use the binding name `USERS_NOTIFICATION_CONFIG`.
🌀 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
+
}
137
155
```
138
156
139
157
</Steps>
@@ -163,17 +181,17 @@ To bind your KV namespace to your Worker:
163
181
164
182
```toml
165
183
[[kv_namespaces]]
166
-
binding = "<BINDING_NAME>"
184
+
binding = "USERS_NOTIFICATION_CONFIG"
167
185
id = "<BINDING_ID>"
168
186
```
169
187
170
188
</WranglerConfig>
171
189
172
190
Binding names do not need to correspond to the namespace you created. Binding names are only a reference. Specifically:
173
191
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`.
175
193
- 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`.
177
195
</Steps>
178
196
179
197
:::note[Bindings]
@@ -201,7 +219,7 @@ Refer to [Environment](/kv/reference/environments/) for more information.
201
219
202
220
You can interact with your KV namespace via [Wrangler](/workers/wrangler/install-and-update/) or directly from your [Workers](/workers/) application.
203
221
204
-
### Write a value
222
+
### 4.1. Write a value
205
223
206
224
<TabssyncKey='CLIvsDash'><TabItemlabel='CLI'>
207
225
@@ -214,24 +232,29 @@ To write a value to your empty KV namespace using Wrangler:
214
232
npx wrangler kv key put --binding=<BINDING_NAME>"<KEY>""<VALUE>"
215
233
```
216
234
235
+
```sh
236
+
npx wrangler kv key put --binding=USERS_NOTIFICATION_CONFIG "user_1""enabled"
237
+
```
217
238
```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>.
219
240
```
220
241
</Steps>
221
242
243
+
:::note
222
244
Instead of using `--binding`, you can also use `--namespace-id` to specify which KV namespace should receive the operation:
223
245
224
-
```sh
246
+
```sh "--namespace-id=<BINDING_ID>"
225
247
npx wrangler kv key put --namespace-id=<BINDING_ID>"<KEY>""<VALUE>"
226
248
```
227
249
228
250
```sh output
229
251
Writing the value "<VALUE>" to key "<KEY>" on namespace <BINDING_ID>.
230
252
```
253
+
:::
231
254
232
255
To create a key and a value in local mode, add the `--local` flag at the end of the command:
233
256
234
-
```sh
257
+
```sh ins="--local"
235
258
npx wrangler kv key put --namespace-id=xxxxxxxxxxxxxxxx "<KEY>""<VALUE>" --local
returnnewResponse("Value not found", { status: 404 });
355
-
}
356
-
returnnewResponse(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
-
returnnewResponse(err, { status: 500 });
362
-
}
363
-
},
364
-
} satisfiesExportedHandler<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
+
/>
366
380
367
381
The code above:
368
382
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.
370
384
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
385
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
386
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
-
383
387
</TabItem><TabItemlabel='Dashboard'>
384
388
385
389
<Steps>
@@ -388,25 +392,14 @@ The browser should simply return the `VALUE` corresponding to the `KEY` you have
388
392
3. Select **Edit Code**.
389
393
4. Clear the contents of the `workers.js` file, then paste the following code.
390
394
391
-
```js
392
-
exportdefault {
393
-
asyncfetch(request, env, ctx) {
394
-
try {
395
-
awaitenv.BINDING_NAME.put("KEY", "VALUE");
396
-
constvalue=awaitenv.BINDING_NAME.get("KEY");
397
-
if (value ===null) {
398
-
returnnewResponse("Value not found", { status:404 });
399
-
}
400
-
returnnewResponse(value);
401
-
} catch (err) {
402
-
// In a production application, you could instead choose to retry your KV
@@ -423,13 +416,38 @@ The browser should simply return the `VALUE` corresponding to the `KEY` you have
423
416
424
417
## 6. Deploy your KV
425
418
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
+
426
444
<TabssyncKey='CLIvsDash'><TabItemlabel='CLI'>
427
445
428
446
<Steps>
429
447
1. Run the following command to deploy KV to Cloudflare's global network:
430
448
431
449
```sh
432
-
npx wrangler deploy
450
+
npm run deploy
433
451
```
434
452
435
453
2. Visit the URL for your newly created Workers KV application.
0 commit comments