Skip to content

Latest commit

 

History

History
460 lines (313 loc) · 15.1 KB

get-started.mdx

File metadata and controls

460 lines (313 loc) · 15.1 KB
title pcx_content_type sidebar
Getting started
get-started
order
2

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

Deploy to Workers

If you want to learn more, continue reading.

This guide instructs you through:

  • Creating a KV namespace.
  • Writing key-value pairs to your KV namespace from a Cloudflare Worker.
  • Reading key-value pairs from a KV namespace.

You can perform these tasks through the CLI or through the Cloudflare dashboard.

Prerequisites

1. Create a Worker project

:::note[New to Workers?]

Refer to How Workers works to learn about the Workers serverless execution model works. Go to the Workers Get started guide to set up your first Worker.

:::

Create a new Worker to read and write to your KV namespace.

1. Create a new project named `kv-tutorial` by running:
<PackageManagers type="create" pkg="cloudflare@latest" args={"kv-tutorial"} />

<Render
	file="c3-post-run-steps"
	product="workers"
	params={{
	category: "hello-world",
	type: "Worker only",
	lang: "TypeScript",
	}}
/>

This creates a new `kv-tutorial` directory, illustrated below.

<FileTree>
	- kv-tutorial/
		- node_modules/
		- test/
		- src
			- **index.ts**
		- package-lock.json
		- package.json
		- testconfig.json
		- vitest.config.mts
		- worker-configuration.d.ts
		- **wrangler.jsonc**
</FileTree>

Your new `kv-tutorial` directory includes:

- A `"Hello World"` [Worker](/workers/get-started/guide/#3-write-code) in `index.ts`.
- A [`wrangler.jsonc`](/workers/wrangler/configuration/) configuration file. `wrangler.jsonc` is how your `kv-tutorial` Worker accesses your kv database.
  1. Change into the directory you just created for your Worker project:

    cd kv-tutorial

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

    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.

    :::

1. Log in to your Cloudflare dashboard and select your account. 2. Go to [your account > **Workers & Pages** > **Overview**](https://dash.cloudflare.com/?to=/:account/workers-and-pages). 3. Select **Create**. 4. Select **Create Worker**. 5. Name your Worker. For this tutorial, name your Worker `kv-tutorial`. 6. Select **Deploy**.

2. Create a KV namespace

A KV namespace is a key-value database replicated to Cloudflare’s global network.

Wrangler allows you to put, list, get, and delete entries within your KV namespace.

:::note

KV operations are scoped to your account. :::

To create a KV namespace via Wrangler:

1. Open your terminal and run the following command:
```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.

For this tutorial, use the binding name `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>"
```

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

3. Bind your Worker to your KV namespace

You must create a binding to connect your Worker with your KV namespace. Bindings allow your Workers to access resources, like KV, on the Cloudflare developer platform.

To bind your KV namespace to your Worker:

  1. In your Wrangler file, add the following with the values generated in your terminal from step 2:

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

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

:::note[Bindings]

A binding is how your Worker interacts with external resources such as 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.

Refer to Environment for more information.

:::

1. Go to [**Workers & Pages** > **Overview**](https://dash.cloudflare.com/?to=/:account/workers-and-pages). 2. Select the `kv-tutorial` Worker you created in [step 1](/kv/get-started/#1-create-a-worker-project). 3. Select **Settings**. 4. Scroll to **Bindings**, then select **Add**. 5. Select **KV namespace**. 6. Name your binding (`BINDING_NAME`) in **Variable name**, then select the KV namespace (`kv_tutorial_namespace`) you created in [step 2](/kv/get-started/#2-create-a-kv-namespace) from the dropdown menu. 7. Select **Deploy** to deploy your binding.

4. Interact with your KV namespace

You can interact with your KV namespace via Wrangler or directly from your Workers application.

Write a value

To write a value to your empty KV namespace using Wrangler:

1. Run the `wrangler kv key put` subcommand in your terminal, and input your key and value respectively. `` and `` are values of your choice.
```sh
npx wrangler kv key put --binding=<BINDING_NAME> "<KEY>" "<VALUE>"
```

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

Instead of using --binding, you can also use --namespace-id to specify which KV namespace should receive the operation:

npx wrangler kv key put --namespace-id=<BINDING_ID> "<KEY>" "<VALUE>"
Writing the value "<VALUE>" to key "<KEY>" on namespace <BINDING_ID>.

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

npx wrangler kv key put --namespace-id=xxxxxxxxxxxxxxxx "<KEY>" "<VALUE>" --local

  1. Go to Storage & Databases > KV.
  2. Select the KV namespace you created (kv_tutorial_namespace), then select View.
  3. Select KV Pairs.
  4. Enter a <KEY> of your choice.
  5. Enter a <VALUE> of your choice.
  6. Select Add entry.

Get a value

To access the value using Wrangler:

1. Run the `wrangler kv key get` subcommand in your terminal, and input your key value:
```sh
# Replace [OPTIONS] with --binding or --namespace-id
npx wrangler kv key get [OPTIONS] "<KEY>"
```

A KV namespace can be specified in two ways:

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

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

</Details>

<Details header ="With a `--namespace-id`">

```sh
npx wrangler kv key get --namespace-id=<YOUR_ID> "<KEY>"
```
</Details>

You can add a --preview flag to interact with a preview namespace instead of a production namespace.

:::caution

Exactly one of --binding or --namespace-id is required. :::

:::note To view the value directly within the terminal, add --text :::

Refer to the kv bulk documentation to write a file of multiple key-value pairs to a given KV namespace.

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

1. Go to your account > **Storage & Databases** > **KV**. 2. Go to the KV namespace you created (`kv_tutorial_namespace`), then select **View**. 3. Select **KV Pairs**.

5. Access your KV namespace from your Worker

:::note

When using wrangler dev to develop locally, Wrangler defaults to using a local version of KV to avoid interfering with any of your live production data in KV. This means that reading keys that you have not written locally returns null.

To have wrangler dev connect to your Workers KV namespace running on Cloudflare's global network, call wrangler dev --remote instead. This uses the preview_id of the KV binding configuration in the Wrangler file. Refer to the KV binding docs for more information.

:::

1. In your Worker script, add your KV binding in the `Env` interface:
```ts
interface Env {
	BINDING_NAME: KVNamespace;
	// ... other binding types
}
```
  1. Use the put() method on BINDING_NAME to create a new key-value pair, or to update the value for a particular key:

    let value = await env.BINDING_NAME.put(key, value);
  2. Use the KV get() method to fetch the data you stored in your KV database:

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

Your Worker code should look like this:

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

To run your project locally, enter the following command within your project directory:

npx wrangler dev

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.

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

1. Go to **Workers & Pages** > **Overview**. 2. Go to the `kv-tutorial` Worker you created. 3. Select **Edit Code**. 4. Clear the contents of the `workers.js` file, then paste the following code.
<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.
  1. Select Save.

6. Deploy your KV

1. Run the following command to deploy KV to Cloudflare's global network:
```sh
npx wrangler deploy
```
  1. Visit the URL for your newly created Workers KV application.

    For example, if the URL of your new Worker is kv-tutorial.<YOUR_SUBDOMAIN>.workers.dev, accessing https://kv-tutorial.<YOUR_SUBDOMAIN>.workers.dev/ sends a request to your Worker that writes (and reads) from Workers KV.

  1. Go to Workers & Pages > Overview.

  2. Select your kv-tutorial Worker.

  3. Select Deployments.

  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.

Summary

By finishing this tutorial, you have:

  1. Created a KV namespace
  2. Created a Worker that writes and reads from that namespace
  3. Deployed your project globally.

Next steps

If you have any feature requests or notice any bugs, share your feedback directly with the Cloudflare team by joining the Cloudflare Developers community on Discord.