Getting started
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 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 Wrangler CLI or through the Cloudflare dashboard.
If you want to skip the setup steps and get started quickly, click on the button below.
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.
You may wish to manually follow the steps if you are new to Cloudflare Workers.
- Sign up for a Cloudflare account ↗.
- 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.
Create a new Worker to read and write to your KV namespace.
-
Create a new project named
kv-tutorial
by running:Terminal window npm create cloudflare@latest -- kv-tutorialTerminal window yarn create cloudflare kv-tutorialTerminal window pnpm create cloudflare@latest kv-tutorialFor setup, select the following options:
- For What would you like to start with?, choose
Hello World Starter
. - For Which template would you like to use?, choose
Worker only
. - 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.jsonc
Your new
kv-tutorial
directory includes:- A
"Hello World"
Worker inindex.ts
. - A
wrangler.jsonc
configuration file.wrangler.jsonc
is how yourkv-tutorial
Worker accesses your kv database.
- For What would you like to start with?, choose
-
Change into the directory you just created for your Worker project:
Terminal window cd kv-tutorial
- Log in to your Cloudflare dashboard and select your account.
- Go to your account > Workers & Pages > Overview ↗.
- Select Create.
- Select Create Worker.
- Name your Worker. For this tutorial, name your Worker
kv-tutorial
. - Select Deploy.
A KV namespace is a key-value database replicated to Cloudflare's global network.
You can use 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.
To create a KV namespace via Wrangler:
-
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 file) and the binding name you provide. A<BINDING_ID>
is randomly generated for you.For this tutorial, use the binding name
USERS_NOTIFICATION_CONFIG
.Terminal window npx wrangler kv namespace create USERS_NOTIFICATION_CONFIG🌀 Creating namespace with title "USERS_NOTIFICATION_CONFIG"✨ Success!Add the following to your configuration file in your kv_namespaces array:{"kv_namespaces": [{"binding": "USERS_NOTIFICATION_CONFIG","id": "<BINDING_ID>"}]}
- Go to Storage & Databases > KV ↗.
- Select Create a namespace.
- Enter a name for your namespace. For this tutorial, use
kv_tutorial_namespace
. - Select Add.
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:
-
In your Wrangler file, add the following with the values generated in your terminal from step 2:
{"kv_namespaces": [{"binding": "USERS_NOTIFICATION_CONFIG","id": "<BINDING_ID>"}]}[[kv_namespaces]]binding = "USERS_NOTIFICATION_CONFIG"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
is used to reference this KV namespace in your Worker. For this tutorial, this should beUSERS_NOTIFICATION_CONFIG
. - The binding must be a valid JavaScript variable name ↗. For example,
binding = "MY_KV"
orbinding = "routingConfig"
would both be valid names for the binding. - Your binding is available in your Worker at
env.<BINDING_NAME>
from within your Worker. For this tutorial, the binding is available atenv.USERS_NOTIFICATION_CONFIG
.
- The value (string) you set for
- Go to Workers & Pages > Overview ↗.
- Select the
kv-tutorial
Worker you created in step 1. - Select Settings.
- Scroll to Bindings, then select Add.
- Select KV namespace.
- Name your binding (
BINDING_NAME
) in Variable name, then select the KV namespace (kv_tutorial_namespace
) you created in step 2 from the dropdown menu. - Select Deploy to deploy your binding.
You can interact with your KV namespace via Wrangler or directly from your Workers application.
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.Terminal window npx wrangler kv key put --binding=<BINDING_NAME> "<KEY>" "<VALUE>"In this tutorial, you will add a key
user_1
with valueenabled
to the KV namespace you created in step 2.Terminal window npx wrangler kv key put --binding=USERS_NOTIFICATION_CONFIG "user_1" "enabled"Writing the value "enabled" to key "user_1" on namespace <BINDING_ID>.
- Go to Storage & Databases > KV ↗.
- Select the KV namespace you created (
kv_tutorial_namespace
), then select View. - Select KV Pairs.
- Enter a
<KEY>
of your choice. - Enter a
<VALUE>
of your choice. - Select Add entry.
To access the value from your KV namespace using Wrangler:
-
Run the
wrangler kv key get
subcommand in your terminal, and input your key value:Terminal window npx wrangler kv key get --binding=<BINDING_NAME> "<KEY>"In this tutorial, you will get the value of the key
user_1
from the KV namespace you created in step 2.Terminal window npx wrangler kv key get --binding=USERS_NOTIFICATION_CONFIG "user_1" --textSimilar to the
put
command, theget
command can also be used to access a KV namespace in two ways - with--binding
or--namespace-id
:
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.
- Go to your account > Storage & Databases > KV.
- Go to the KV namespace you created (
kv_tutorial_namespace
), then select View. - Select KV Pairs.
-
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.interface Env {USERS_NOTIFICATION_CONFIG: KVNamespace;// ... other binding types} -
Use the
put()
method onUSERS_NOTIFICATION_CONFIG
to create a new key-value pair. You will add a new keyuser_2
with valuedisabled
to your KV namespace.let value = await env.USERS_NOTIFICATION_CONFIG.put("user_2", "disabled"); -
Use the KV
get()
method to fetch the data you stored in your KV namespace. You will fetch the value of the keyuser_2
from your KV namespace.let value = await env.USERS_NOTIFICATION_CONFIG.get("user_2");
Your Worker code should look like this:
export default { async fetch(request, env, ctx) { try { await env.USER_NOTIFICATION.put("user_2", "disabled"); const value = await env.USER_NOTIFICATION.get("user_2"); if (value === null) { return new Response("Value not found", { status: 404 }); } return new Response(value); } catch (err) { console.error(`KV returned error:`, err); const errorMessage = err instanceof Error ? err.message : "An unknown error occurred when accessing KV storage"; return new Response(errorMessage, { status: 500, headers: { "Content-Type": "text/plain" }, }); } },};
export interface Env { USER_NOTIFICATION: KVNamespace;}
export default { async fetch(request, env, ctx): Promise<Response> { try { await env.USER_NOTIFICATION.put("user_2", "disabled"); const value = await env.USER_NOTIFICATION.get("user_2"); if (value === null) { return new Response("Value not found", { status: 404 }); } return new Response(value); } catch (err) { console.error(`KV returned error:`, err); const errorMessage = err instanceof Error ? err.message : "An unknown error occurred when accessing KV storage"; return new Response(errorMessage, { status: 500, headers: { "Content-Type": "text/plain" }, }); } },} satisfies ExportedHandler<Env>;
The code above:
- Writes a key to your KV namespace using KV's
put()
method. - Reads the same key using KV's
get()
method. - Checks if the key is null, and returns a
404
response if it is. - If the key is not null, it returns the value of the key.
- 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 usingfetch()
, you should expect to handle exceptions explicitly.
-
Go to Workers & Pages > Overview.
-
Go to the
kv-tutorial
Worker you created. -
Select Edit Code.
-
Clear the contents of the
workers.js
file, then paste the following code.export default {async fetch(request, env, ctx) {try {await env.USER_NOTIFICATION.put("user_2", "disabled");const value = await env.USER_NOTIFICATION.get("user_2");if (value === null) {return new Response("Value not found", { status: 404 });}return new Response(value);} catch (err) {console.error(`KV returned error:`, err);const errorMessage =err instanceof Error? err.message: "An unknown error occurred when accessing KV storage";return new Response(errorMessage, {status: 500,headers: { "Content-Type": "text/plain" },});}},};export interface Env {USER_NOTIFICATION: KVNamespace;}export default {async fetch(request, env, ctx): Promise<Response> {try {await env.USER_NOTIFICATION.put("user_2", "disabled");const value = await env.USER_NOTIFICATION.get("user_2");if (value === null) {return new Response("Value not found", { status: 404 });}return new Response(value);} catch (err) {console.error(`KV returned error:`, err);const errorMessage =err instanceof Error? err.message: "An unknown error occurred when accessing KV storage";return new Response(errorMessage, {status: 500,headers: { "Content-Type": "text/plain" },});}},} satisfies ExportedHandler<Env>;The code above:
- Writes a key to
BINDING_NAME
using KV'sput()
method. - 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). - 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 usingfetch()
, you should expect to handle exceptions explicitly.
The browser should simply return the
VALUE
corresponding to theKEY
you have specified with theget()
method. - Writes a key to
-
Select Save.
Deploy your Worker to Cloudflare's global network.
-
Run the following command to deploy KV to Cloudflare's global network:
Terminal window npm run deploy -
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
, accessinghttps://kv-tutorial.<YOUR_SUBDOMAIN>.workers.dev/
sends a request to your Worker that writes (and reads) from Workers KV.
-
Go to Workers & Pages > Overview.
-
Select your
kv-tutorial
Worker. -
Select Deployments.
-
From the Version History table, select Deploy version.
-
From the Deploy version page, select Deploy.
This deploys the latest version of the Worker code to production.
By finishing this tutorial, you have:
- Created a KV namespace
- Created a Worker that writes and reads from that namespace
- Deployed your project globally.
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 ↗.
- Learn more about the KV API.
- Understand how to use Environments with Workers KV.
- Read the Wrangler
kv
command documentation.
Was this helpful?
- Resources
- API
- New to Cloudflare?
- Products
- Sponsorships
- Open Source
- Support
- Help Center
- System Status
- Compliance
- GDPR
- Company
- cloudflare.com
- Our team
- Careers
- 2025 Cloudflare, Inc.
- Privacy Policy
- Terms of Use
- Report Security Issues
- Trademark