Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Test new pattern on kv get started #21229

Draft
wants to merge 3 commits into
base: production
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
217 changes: 104 additions & 113 deletions src/content/docs/kv/get-started.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,26 @@ sidebar:
order: 2
---

import { Render, PackageManagers, Steps, FileTree, Details, Tabs, TabItem, WranglerConfig } from "~/components";
import {
Render,
PackageManagers,
Steps,
FileTree,
Details,
Tabs,
TabItem,
WranglerConfig,
GitHubCode,
} from "~/components";

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.

If you want to deploy the example right away, use the button below and skip to [Step 6](#6-deploy-your-kv).

[![Deploy to Workers](https://deploy.workers.cloudflare.com/button)](https://deploy.workers.cloudflare.com/?url=https://github.com/cloudflare/docs-examples/tree/main/kv-get-started)

If you want to learn more, [continue reading](#prerequisites).

This guide instructs you through:

- Creating a KV namespace.
Expand Down Expand Up @@ -71,17 +87,17 @@ Create a new Worker to read and write to your KV namespace.

2. Change into the directory you just created for your Worker project:

```sh
cd kv-tutorial
```
```sh
cd kv-tutorial
```

:::note
:::note

If you are familiar with Cloudflare Workers, or initializing projects in a Continuous Integration (CI) environment, initialize a new project non-interactively by setting `CI=true` as an environmental variable when running `create cloudflare@latest`.
If you are familiar with Cloudflare Workers, or initializing projects in a Continuous Integration (CI) environment, initialize a new project non-interactively by setting `CI=true` as an environmental variable when running `create cloudflare@latest`.

For example: `CI=true npm create cloudflare@latest kv-tutorial --type=simple --git --ts --deploy=false` creates a basic "Hello World" project ready to build on.
For example: `CI=true npm create cloudflare@latest kv-tutorial --type=simple --git --ts --deploy=false` creates a basic "Hello World" project ready to build on.

:::
:::

</Steps>
</TabItem> <TabItem label = 'Dashboard'>
Expand Down Expand Up @@ -115,36 +131,36 @@ To create a KV namespace via Wrangler:
<Steps>
1. Open your terminal and run the following command:

```sh
npx wrangler kv namespace create <BINDING_NAME>
```
```sh
npx wrangler kv namespace create <BINDING_NAME>
```

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.
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.

For this tutorial, use the binding name `BINDING_NAME`.
For this tutorial, use the binding name `BINDING_NAME`.

```sh
npx wrangler kv namespace create BINDING_NAME
```
```sh
npx wrangler kv namespace create BINDING_NAME
```

```sh output
🌀 Creating namespace with title kv-tutorial-BINDING_NAME
✨ Success!
Add the following to your configuration file:
[[kv_namespaces]]
binding = "BINDING_NAME"
id = "<BINDING_ID>"
```
```sh output
🌀 Creating namespace with title kv-tutorial-BINDING_NAME
✨ Success!
Add the following to your configuration file:
[[kv_namespaces]]
binding = "BINDING_NAME"
id = "<BINDING_ID>"
```

</Steps>

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

<Steps>
1. Go to [**Storage & Databases** > **KV**](https://dash.cloudflare.com/?to=/:account/workers/kv/namespaces).
2. Select **Create a namespace**.
3. Enter a name for your namespace. For this tutorial, use `kv_tutorial_namespace`.
4. Select **Add**.
1. Go to [**Storage & Databases** >
**KV**](https://dash.cloudflare.com/?to=/:account/workers/kv/namespaces). 2.
Select **Create a namespace**. 3. Enter a name for your namespace. For this
tutorial, use `kv_tutorial_namespace`. 4. Select **Add**.
</Steps>

</TabItem></Tabs>
Expand All @@ -159,21 +175,22 @@ To bind your KV namespace to your Worker:
<Steps>
1. In your Wrangler file, add the following with the values generated in your terminal from [step 2](/kv/get-started/#2-create-a-kv-namespace):

<WranglerConfig>
<WranglerConfig>

```toml
[[kv_namespaces]]
binding = "<BINDING_NAME>"
id = "<BINDING_ID>"
```

```toml
[[kv_namespaces]]
binding = "<BINDING_NAME>"
id = "<BINDING_ID>"
```
</WranglerConfig>

</WranglerConfig>
Binding names do not need to correspond to the namespace you created. Binding names are only a reference. Specifically:

Binding names do not need to correspond to the namespace you created. Binding names are only a reference. Specifically:
- 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`.
- 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.
- Your binding is available in your Worker at `env.<BINDING_NAME>` from within your Worker.

- 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`.
- 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.
- Your binding is available in your Worker at `env.<BINDING_NAME>` from within your Worker.
</Steps>

:::note[Bindings]
Expand Down Expand Up @@ -210,13 +227,14 @@ To write a value to your empty KV namespace using Wrangler:
<Steps>
1. Run the `wrangler kv key put` subcommand in your terminal, and input your key and value respectively. `<KEY>` and `<VALUE>` are values of your choice.

```sh
npx wrangler kv key put --binding=<BINDING_NAME> "<KEY>" "<VALUE>"
```
```sh
npx wrangler kv key put --binding=<BINDING_NAME> "<KEY>" "<VALUE>"
```

```sh output
Writing the value "<VALUE>" to key "<KEY>" on namespace <BINDING_ID>.
```

```sh output
Writing the value "<VALUE>" to key "<KEY>" on namespace <BINDING_ID>.
```
</Steps>

Instead of using `--binding`, you can also use `--namespace-id` to specify which KV namespace should receive the operation:
Expand Down Expand Up @@ -265,9 +283,9 @@ To access the value using Wrangler:

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

```sh
npx wrangler kv key get --binding=<BINDING_NAME> "<KEY>"
```
```sh
npx wrangler kv key get --binding=<BINDING_NAME> "<KEY>"
```

</Details>

Expand Down Expand Up @@ -296,6 +314,7 @@ Refer to the [`kv bulk` documentation](/kv/reference/kv-commands/#kv-bulk) to wr
</TabItem><TabItem label='Dashboard'>

You can view key-value pairs directly from the dashboard.

<Steps>
1. Go to your account > **Storage & Databases** > **KV**.
2. Go to the KV namespace you created (`kv_tutorial_namespace`), then select **View**.
Expand All @@ -318,51 +337,35 @@ To have `wrangler dev` connect to your Workers KV namespace running on Cloudflar
<Steps>
1. In your Worker script, add your KV binding in the `Env` interface:

```ts
interface Env {
BINDING_NAME: KVNamespace;
// ... other binding types
}
```
```ts
interface Env {
BINDING_NAME: KVNamespace;
// ... other binding types
}
```

2. Use the `put()` method on `BINDING_NAME` to create a new key-value pair, or to update the value for a particular key:
2. Use the `put()` method on `BINDING_NAME` to create a new key-value pair, or to update the value for a particular key:

```ts
let value = await env.BINDING_NAME.put(key, value);
```
```ts
let value = await env.BINDING_NAME.put(key, value);
```

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

```ts
let value = await env.BINDING_NAME.get("KEY");
```

```ts
let value = await env.BINDING_NAME.get("KEY");
```
</Steps>

Your Worker code should look like this:

```ts
export interface Env {
BINDING_NAME: KVNamespace;
}

export default {
async fetch(request, env, ctx): Promise<Response> {
try {
await env.BINDING_NAME.put("KEY", "VALUE");
const value = await env.BINDING_NAME.get("KEY");
if (value === null) {
return new Response("Value not found", { status: 404 });
}
return new Response(value);
} catch (err) {
// In a production application, you could instead choose to retry your KV
// read or fall back to a default code path.
console.error(`KV returned error: ${err}`);
return new Response(err, { status: 500 });
}
},
} satisfies ExportedHandler<Env>;
```
<GitHubCode
repo="cloudflare/docs-examples"
file="kv-get-started/src/index.ts"
commit="6c967adfa2c1d5747f90aed7c021753ca07b935c"
lang="ts"
/>

The code above:

Expand All @@ -388,33 +391,21 @@ The browser should simply return the `VALUE` corresponding to the `KEY` you have
3. Select **Edit Code**.
4. Clear the contents of the `workers.js` file, then paste the following code.

```js
export default {
async fetch(request, env, ctx) {
try {
await env.BINDING_NAME.put("KEY", "VALUE");
const value = await env.BINDING_NAME.get("KEY");
if (value === null) {
return new Response("Value not found", { status: 404 });
}
return new Response(value);
} catch (err) {
// In a production application, you could instead choose to retry your KV
// read or fall back to a default code path.
console.error(`KV returned error: ${err}`);
return new Response(err.toString(), { status: 500 });
}
},
};
```

The code above:

1. Writes a key to `BINDING_NAME` using KV's `put()` method.
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).
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.

The browser should simply return the `VALUE` corresponding to the `KEY` you have specified with the `get()` method.
<GitHubCode
repo="cloudflare/docs-examples"
file="kv-get-started/src/index.ts"
commit="6c967adfa2c1d5747f90aed7c021753ca07b935c"
lang="js"
/>

The code above:

1. Writes a key to `BINDING_NAME` using KV's `put()` method.
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).
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.

The browser should simply return the `VALUE` corresponding to the `KEY` you have specified with the `get()` method.

2. Select **Save**.

</Steps>
Expand Down Expand Up @@ -447,7 +438,7 @@ The browser should simply return the `VALUE` corresponding to the `KEY` you have
4. From the **Version History** table, select **Deploy version**.
5. From the **Deploy version** page, select **Deploy**.

This deploys the latest version of the Worker code to production.
This deploys the latest version of the Worker code to production.

</Steps>
</TabItem></Tabs>
Expand Down
Loading