Cloudflare Docs
KV
Edit this page on GitHub
Set theme to dark (⇧+D)

Get started

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.

This guide will instruct 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.

​​ Prerequisites

To continue:

  1. Sign up for a Cloudflare account if you have not already.
  2. Install npm.
  3. Install Node.js. Use a Node version manager like Volta or nvm to avoid permission issues and change Node.js versions. Wrangler requires a Node version of 16.13.0 or later.

​​ 1. Enable Workers KV in the dashboard

Enable Workers KV for your account by purchasing the Workers Paid plan:

  1. Log in to the Cloudflare dashboard and select your account.
  2. Go to Workers & Pages > Plans.
  3. Select Purchase Workers Paid and complete the payment process to enable Workers KV.

​​ 2. Create a Worker project

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

Create a new project named kv-tutorial by running:

$ npm create cloudflare@latest kv-tutorial

When setting up your kv-tutorial Worker, answer the questions as below:

  • Your directory has been titled kv-tutorial.
  • Choose "Hello World" Worker for the type of application.
  • Select yes to using TypeScript.
  • Select yes to using Git.
  • Select no to deploying.

This will create a new kv-tutorial directory. Your new kv-tutorial directory will include:

  • A "Hello World" Worker at src/index.ts.
  • A wrangler.toml configuration file. wrangler.toml is how your kv-tutorial Worker will access your kv database.

​​ 3. Create a KV namespace

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

You can create a KV namespace via Wrangler or the dashboard.

​​ Create a KV namespace via Wrangler

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

To create a KV namespace via Wrangler:

  1. Open your terminal and run the following command:
$ wrangler kv:namespace create <YOUR_NAMESPACE>

The wrangler kv:namespace create <YOUR_NAMESPACE> subcommand takes a new binding name as its argument. A KV namespace will be created using a concatenation of your Worker’s name (from your wrangler.toml file) and the binding name you provide. The id will be randomly generated for you.

$ wrangler kv:namespace create <YOUR_NAMESPACE>
🌀 Creating namespace with title <YOUR_WORKER-YOUR_NAMESPACE>
✨ Success!
Add the following to your configuration file:
kv_namespaces = [
{ binding = <YOUR_BINDING>, id = "e29b263ab50e42ce9b637fa8370175e8" }
]
  1. In your wrangler.toml file, add the following with the values generated in your terminal:
wrangler.toml
kv_namespaces = [
{ binding = "<YOUR_BINDING>", id = "<YOUR_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> will be used to reference this database in your Worker. In this tutorial, name your binding DB.
  • 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.

​​ Create a KV namespace via the dashboard

  1. Log in to the Cloudflare dashboard.
  2. Select Workers & Pages > KV.
  3. Select Create a namespace.
  4. Enter a name for your namespace.
  5. Select Add.

​​ 4. Interact with your KV namespace

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

​​ Write a value via Wrangler

To write a value to your empty KV namespace using Wrangler, 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.

$ wrangler kv:key put --binding=<YOUR_BINDING> "<KEY>" "<VALUE>"
Writing the value "<VALUE>" to key "<KEY>" on namespace e29b263ab50e42ce9b637fa8370175e8.

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

$ wrangler kv:key put --namespace-id=e29b263ab50e42ce9b637fa8370175e8 "<KEY>" "<VALUE>"
Writing the value "<VALUE>" to key "<KEY>" on namespace e29b263ab50e42ce9b637fa8370175e8.

To create a key and a value in local mode, use the --local flag:

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

​​ Get a value via Wrangler

To access the value using Wrangler, run the wrangler kv:key get subcommand in your terminal, and input your key value:

$ wrangler kv:key get <KEY> [OPTIONS] # Replace [OPTIONS] with --binding or --namespace-id

A KV namespace can be specified in two ways:

  • With a --binding:
$ wrangler kv:key get --binding=<YOUR_BINDING> "<KEY>"

This can be combined with --preview flag to interact with a preview namespace instead of a production namespace.

  • With a --namespace-id:
$ wrangler kv:key get --namespace-id=<YOUR_ID> "<KEY>"

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

​​ Interact with your KV namespace via a Worker

You can access the binding from within your Worker.

In your Worker script, add your KV namespace in the Env interface:

interface Env {
YOUR_KV_NAMESPACE: KVNamespace;
// ... other binding types
}

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

let value = await env.YOUR_KV_NAMESPACE.put(key, value);

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

let value = await env.YOUR_KV_NAMESPACE.get("KEY");

Your Worker code should look like this:

src/index.ts
export interface Env {
YOUR_KV_NAMESPACE: KVNamespace;
}
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
try {
await env.YOUR_KV_NAMESPACE.put("KEY", "VALUE");       
const value = await env.YOUR_KV_NAMESPACE.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 })
}
},
};

The code above:

  1. Writes a key to YOUR_KV_NAMESPACE 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.

​​ 5. Develop locally with Wrangler

While in your project directory, test your KV locally by running:

$ npx wrangler dev

When you run wrangler dev, Wrangler will give you a URL (usually a localhost:8787) to review your Worker. After you visit the URL Wrangler provides, you will see your value printed on the browser.

​​ 6. Deploy your KV

Run the following command to deploy KV to Cloudflare’s global network:

$ npx wrangler deploy

You can now 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/ will send a request to your Worker that writes (and reads) from Workers KV.

By finishing this tutorial, you have created a KV namespace, a Worker that writes and reads from that namespace, and 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.