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
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,11 +112,11 @@ 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
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.
107
120
108
121
:::note
109
122
@@ -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>
@@ -153,6 +171,14 @@ To create a KV namespace via Wrangler:
153
171
154
172
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.
155
173
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
+
156
182
To bind your KV namespace to your Worker:
157
183
158
184
<TabssyncKey='CLIvsDash'><TabItemlabel='CLI'>
@@ -163,27 +189,19 @@ To bind your KV namespace to your Worker:
163
189
164
190
```toml
165
191
[[kv_namespaces]]
166
-
binding = "<BINDING_NAME>"
192
+
binding = "USERS_NOTIFICATION_CONFIG"
167
193
id = "<BINDING_ID>"
168
194
```
169
195
170
196
</WranglerConfig>
171
197
172
198
Binding names do not need to correspond to the namespace you created. Binding names are only a reference. Specifically:
173
199
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`.
175
201
- 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`.
177
203
</Steps>
178
204
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
-
187
205
</TabItem><TabItemlabel='Dashboard'>
188
206
189
207
<Steps>
@@ -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,27 +232,38 @@ 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
+
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
+
```
217
240
```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>.
219
242
```
220
243
</Steps>
221
244
245
+
:::note[Using `--namespace-id`]
222
246
Instead of using `--binding`, you can also use `--namespace-id` to specify which KV namespace should receive the operation:
223
247
224
-
```sh
248
+
```sh "--namespace-id=<BINDING_ID>"
225
249
npx wrangler kv key put --namespace-id=<BINDING_ID>"<KEY>""<VALUE>"
226
250
```
227
251
228
252
```sh output
229
253
Writing the value "<VALUE>" to key "<KEY>" on namespace <BINDING_ID>.
230
254
```
255
+
:::
231
256
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]
233
258
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
236
263
```
237
264
265
+
:::
266
+
238
267
</TabItem><TabItemlabel='Dashboard'>
239
268
<Steps>
240
269
1. Go to [**Storage & Databases** > **KV**](https://dash.cloudflare.com/?to=/:account/workers/kv/namespaces).
To access the value from your KV namespace using Wrangler:
255
284
256
285
<Steps>
257
286
1. Run the `wrangler kv key get` subcommand in your terminal, and input your key value:
258
287
259
288
```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>"
262
290
```
263
291
264
-
A KV namespace can be specified in two ways:
265
-
266
-
<Detailsheader="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).
271
293
272
-
</Details>
273
-
274
-
<Detailsheader="With a `--namespace-id`">
294
+
:::note
295
+
To view the value directly within the terminal, you use the `--text` flag.
296
+
:::
275
297
276
298
```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
278
300
```
279
-
</Details>
280
301
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`:
282
303
283
-
You can add a `--preview` flag to interact with a preview namespace instead of a production namespace.
304
+
</Steps>
284
305
285
306
:::caution
286
307
287
308
Exactly **one** of `--binding` or `--namespace-id` is required.
288
309
:::
289
310
290
-
:::note
291
-
To view the value directly within the terminal, add `--text`
292
-
:::
293
-
294
311
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.
295
312
296
313
</TabItem><TabItemlabel='Dashboard'>
@@ -316,69 +333,46 @@ To have `wrangler dev` connect to your Workers KV namespace running on Cloudflar
316
333
:::
317
334
318
335
<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.
320
337
321
338
```ts
322
339
interfaceEnv {
323
-
BINDING_NAME:KVNamespace;
340
+
USERS_NOTIFICATION_CONFIG:KVNamespace;
324
341
// ... other binding types
325
342
}
326
343
```
327
344
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.
329
346
330
347
```ts
331
-
let value =awaitenv.BINDING_NAME.put(key, value);
348
+
let value =awaitenv.USERS_NOTIFICATION_CONFIG.put("user_2", "disabled");
332
349
```
333
350
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.
335
352
336
353
```ts
337
-
let value =awaitenv.BINDING_NAME.get("KEY");
354
+
let value =awaitenv.USERS_NOTIFICATION_CONFIG.get("user_2");
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
-
```
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
+
/>
366
368
367
369
The code above:
368
370
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.
382
376
383
377
</TabItem><TabItemlabel='Dashboard'>
384
378
@@ -388,25 +382,14 @@ The browser should simply return the `VALUE` corresponding to the `KEY` you have
388
382
3. Select **Edit Code**.
389
383
4. Clear the contents of the `workers.js` file, then paste the following code.
390
384
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
0 commit comments