Getting 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 Wrangler CLI or through the Cloudflare dashboard.
Quick start
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.
Prerequisites
- Sign up for a Cloudflare account.
- Install
Node.js.
Node.js version manager
Use Vite+ (vp env) to install and manage Node.js versions.
For supported Node.js versions, refer to the Wrangler system requirements.
1. Create a Worker project
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.
CLIDashboard
Create a new Worker to read and write to your KV namespace.
-
Create a new project named
kv-tutorialby running:npmyarnpnpm
npm create cloudflare@latest -- kv-tutorialyarn create cloudflare kv-tutorialpnpm create cloudflare@latest kv-tutorialFor 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
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 add an AGENTS.md file to help AI coding tools understand Cloudflare APIs?, 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-tutorialdirectory, illustrated below.kv-tutorial/
- node_modules/
- test/
src
- index.ts
- package-lock.json
- package.json
- testconfig.json
- vitest.config.mts
- worker-configuration.d.ts
- wrangler.jsonc
Your new
kv-tutorialdirectory includes:- A
"Hello World"Worker inindex.ts. - A
wrangler.jsoncconfiguration file.wrangler.jsoncis how yourkv-tutorialWorker accesses your kv database.
- For What would you like to start with?, choose
-
Change into the directory you just created for your Worker project:
cd kv-tutorialNote
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=trueas an environmental variable when runningcreate cloudflare@latest.For example:
CI=true npm create cloudflare@latest kv-tutorial --type=simple --git --ts --deploy=falsecreates a basic "Hello World" project ready to build on.
-
In the Cloudflare dashboard, go to the Workers & Pages page.
-
Select Create application.
-
Select Start with Hello World! > Get started.
-
Name your Worker. For this tutorial, name your Worker
kv-tutorial. -
Select Deploy.
2. Create a KV namespace
A KV namespace is a key-value database replicated to Cloudflare's global network.
CLIDashboard
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.
Note
KV operations are scoped to your account.
To create a KV namespace via Wrangler:
-
Open your terminal and run the following command:
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.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>" } ] }
-
In the Cloudflare dashboard, go to the Workers KV page.
-
Select Create instance.
-
Enter a name for your namespace. For this tutorial, use
kv_tutorial_namespace. -
Select Create.
KV Instant namespaces
Note
Workers KV Instant is currently in private beta. To enroll, contact your Cloudflare account team or sign up and tell us about your use case.
Use Workers KV Instant for small, read-heavy application configurations values that update infrequently and are proactively propagated across Cloudflare's network.
To optionally create a KV Instant namespace named APP_CONFIG with Wrangler, pass --experimental-mode instant:
npmyarnpnpm
npx wrangler@latest kv namespace create APP_CONFIG --experimental-mode instantyarn wrangler@latest kv namespace create APP_CONFIG --experimental-mode instantpnpm wrangler@latest kv namespace create APP_CONFIG --experimental-mode instantTo create the namespace with Cloudflare CLI, pass --namespaceMode instant:
cf kv namespaces create --title APP_CONFIG --namespaceMode instantAlternatively, create it through the API with mode: "instant":
curl "https://api.cloudflare.com/client/v4/accounts/$ACCOUNT_ID/storage/kv/namespaces" \
--request POST \
--header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
--json '{
"title": "APP_CONFIG",
"mode": "instant"
}'KV Instance namespaces have additional limitations compared to classic namespaces. Refer to KV Instant limits before choosing this mode.
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.
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.
To bind your KV namespace to your Worker:
CLIDashboard
-
In your Wrangler file, add the following with the values generated in your terminal from step 2:
wrangler.jsoncwrangler.toml
{ "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
bindingis 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
-
In the Cloudflare dashboard, go to the Workers & Pages page.
-
Select the
kv-tutorialWorker you created in step 1. -
Got to the Bindings tab, then select Add binding.
-
Select KV namespace > Add binding.
-
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 Add binding 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.
4.1. Write a value
CLIDashboard
To write a value to your empty KV namespace using Wrangler:
-
Run the
wrangler kv key putsubcommand in your terminal, and input your key and value respectively.<KEY>and<VALUE>are values of your choice.npx wrangler kv key put --binding=<BINDING_NAME> "<KEY>" "<VALUE>"In this tutorial, you will add a key
user_1with valueenabledto the KV namespace you created in step 2.npx wrangler kv key put --binding=USERS_NOTIFICATION_CONFIG "user_1" "enabled"Writing the value "enabled" to key "user_1" on namespace <BINDING_ID>.
Using `--namespace-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>.Storing values in remote KV namespace
By default, the values are written locally. To create a key and a value in your remote KV namespace, add the --remote flag at the end of the command:
npx wrangler kv key put --namespace-id=xxxxxxxxxxxxxxxx "<KEY>" "<VALUE>" --remote-
In the Cloudflare dashboard, go to the Workers KV page.
-
Select the KV namespace you created (
kv_tutorial_namespace). -
Go to the KV Pairs tab.
-
Enter a
<KEY>of your choice. -
Enter a
<VALUE>of your choice. -
Select Add entry.
4.2. Get a value
CLIDashboard
To access the value from your KV namespace using Wrangler:
-
Run the
wrangler kv key getsubcommand in your terminal, and input your key value:npx wrangler kv key get --binding=<BINDING_NAME> "<KEY>"In this tutorial, you will get the value of the key
user_1from the KV namespace you created in step 2.Note
To view the value directly within the terminal, you use the
--textflag.npx wrangler kv key get --binding=USERS_NOTIFICATION_CONFIG "user_1" --textSimilar to the
putcommand, thegetcommand can also be used to access a KV namespace in two ways - with--bindingor--namespace-id:
Caution
Exactly one of --binding or --namespace-id is required.
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.
-
In the Cloudflare dashboard, go to the Workers KV page.
-
Go to the KV namespace you created (
kv_tutorial_namespace). -
Go to the KV Pairs tab.
5. Access your KV namespace from your Worker
CLIDashboard
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, you can set "remote" : true in the KV binding configuration. Refer to the remote bindings documentation for more information.
Also refer to KV binding docs.
-
In your Worker script, add your KV binding in the
Envinterface. 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_CONFIGto create a new key-value pair. You will add a new keyuser_2with valuedisabledto 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_2from your KV namespace.let value = await env.USERS_NOTIFICATION_CONFIG.get("user_2");
Your Worker code should look like this:
JavaScriptTypeScript
export default {
async fetch(request, env, ctx) {
try {
await env.USERS_NOTIFICATION_CONFIG.put("user_2", "disabled");
const value = await env.USERS_NOTIFICATION_CONFIG.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 {
USERS_NOTIFICATION_CONFIG: KVNamespace;
}
export default {
async fetch(request, env, ctx): Promise<Response> {
try {
await env.USERS_NOTIFICATION_CONFIG.put("user_2", "disabled");
const value = await env.USERS_NOTIFICATION_CONFIG.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
404response if it is. - If the key is not null, it returns the value of the key.
- Uses JavaScript's
try...catchexception 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.
-
In the Cloudflare dashboard, go to the Workers & Pages page.
-
Go to the
kv-tutorialWorker you created. -
Select Edit Code.
-
Clear the contents of the
workers.jsfile, then paste the following code.JavaScriptTypeScript
export default { async fetch(request, env, ctx) { try { await env.USERS_NOTIFICATION_CONFIG.put("user_2", "disabled"); const value = await env.USERS_NOTIFICATION_CONFIG.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 { USERS_NOTIFICATION_CONFIG: KVNamespace; } export default { async fetch(request, env, ctx): Promise<Response> { try { await env.USERS_NOTIFICATION_CONFIG.put("user_2", "disabled"); const value = await env.USERS_NOTIFICATION_CONFIG.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_NAMEusing 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...catchexception 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
VALUEcorresponding to theKEYyou have specified with theget()method. - Writes a key to
-
Select the dropdown arrow next to Deploy and select Save.
6. Deploy your Worker
Deploy your Worker to Cloudflare's global network.
CLIDashboard
-
Run the following command to deploy KV to Cloudflare's global network:
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.
-
In the Cloudflare dashboard, go to the Workers & Pages page.
-
Select your
kv-tutorialWorker. -
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.
Summary
By finishing this tutorial, you have:
- Created a KV namespace
- Created a Worker that writes and reads from that namespace
- 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.
- Learn more about the KV API.
- Understand how to use Environments with Workers KV.
- Read the Wrangler
kvcommand documentation.