Skip to content

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 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. Sign up for a Cloudflare account.
  2. Install Node.js.

Node.js version manager

Use a Node version manager like Volta or nvm to avoid permission issues and change Node.js versions. Wrangler, discussed later in this guide, requires a Node version of 16.17.0 or later.

1. Create a Worker project

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

  1. Create a new project named kv-tutorial by running:

    Terminal window
    npm create cloudflare@latest -- kv-tutorial

    For setup, select the following options:

    • For What would you like to start with?, choose Hello World example.
    • For Which template would you like to use?, choose Hello World Worker.
    • For Which language do you want to use?, choose TypeScript.
    • For Do you want to use git for version control?, choose Yes.
    • For Do you want to deploy your application?, choose No (we will be making some changes before deploying).

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

    • Directorykv-tutorial/
      • Directorynode_modules/
      • Directorytest/
      • Directorysrc
        • index.ts
      • package-lock.json
      • package.json
      • testconfig.json
      • vitest.config.mts
      • worker-configuration.d.ts
      • wrangler.toml

    Your new kv-tutorial directory includes:

    • A "Hello World" Worker in index.ts.
    • A wrangler.toml configuration file. wrangler.toml is how your kv-tutorial Worker accesses your kv database.
  2. Change into the directory you just created for your Worker project:

    Terminal window
    cd kv-tutorial

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.

To create a KV namespace via Wrangler:

  1. Open your terminal and run the following command:

    Terminal window
    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.toml file) and the binding name you provide. A BINDING_ID is randomly generated for you.

    For this tutorial, use the binding name BINDING_NAME.

    Terminal window
    npx wrangler kv namespace create BINDING_NAME
    🌀 Creating namespace with title kv-tutorial-BINDING_NAME
    Success!
    Add the following to your configuration file:
    [[kv_namespaces]]
    binding = "BINDING_NAME"
    id = "<BINDING_ID>"

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

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. <KEY> and <VALUE> are values of your choice.

    Terminal window
    npx wrangler kv key put --binding=<BINDING_NAME> "<KEY>" "<VALUE>"
    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:

Terminal window
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:

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

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:

    Terminal window
    # Replace [OPTIONS] with --binding or --namespace-id
    npx wrangler kv key get [OPTIONS] "<KEY>"

    A KV namespace can be specified in two ways:

    With a --binding

    Terminal window
    npx wrangler kv key get --binding=<BINDING_NAME> "<KEY>"

    With a --namespace-id

    Terminal window
    npx wrangler kv key get --namespace-id=<YOUR_ID> "<KEY>"

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

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

5. Access your KV namespace from your Worker

  1. In your Worker script, add your KV binding in the Env interface:

    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:

    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:

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

Your Worker code should look like this:

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

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:

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

6. Deploy your KV

  1. Run the following command to deploy KV to Cloudflare's global network:

    Terminal window
    npx wrangler deploy
  2. 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.

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.