### Worker example to list keys and return them Source: https://developers.cloudflare.com/kv/llms-full.txt This example demonstrates how to use the `list()` method within a Worker's `fetch` handler to retrieve keys from a KV namespace and return them as a JSON response. It includes basic error handling. ```javascript export default { async fetch(request, env, ctx) { try { const value = await env.NAMESPACE.list(); return new Response(JSON.stringify(value.keys), { status: 200 }); } catch (e) { return new Response(e.message, {status: 500}); } }, }; ``` -------------------------------- ### Full Worker Example with KV Operations (JavaScript) Source: https://developers.cloudflare.com/kv/get-started/index A complete JavaScript Worker script demonstrating how to put and get data from a KV namespace, including error handling for KV access. ```javascript 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" }, }); } }, }; ``` -------------------------------- ### List Namespace Keys Example Source: https://developers.cloudflare.com/api/resources/kv/index This example demonstrates how to list keys within a Cloudflare KV namespace using a cURL command. Ensure you replace placeholder values with your actual account ID, namespace ID, and API token. ```http curl https://api.cloudflare.com/client/v4/accounts/$ACCOUNT_ID/storage/kv/namespaces/$NAMESPACE_ID/keys \ -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" ``` -------------------------------- ### Example Response for Getting a Namespace Source: https://developers.cloudflare.com/api/resources/kv/index This JSON structure shows a successful response when retrieving details of a single KV namespace. ```json { "errors": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "messages": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "success": true, "result": { "id": "0f2ac74b498b48028cb68387c421e279", "title": "My Own Namespace", "supports_url_encoding": true } } ``` -------------------------------- ### KV get() method signature Source: https://developers.cloudflare.com/kv/llms-full.txt Shows the method signature for get() including optional type and options parameters. ```javascript env.NAMESPACE.get(key, type?); // OR env.NAMESPACE.get(key, options?); ``` -------------------------------- ### Basic KV get() usage Source: https://developers.cloudflare.com/kv/llms-full.txt Demonstrates the basic syntax for reading individual or multiple keys from a KV namespace. ```javascript // Read individual key env.NAMESPACE.get(key); // Read multiple keys env.NAMESPACE.get(keys); ``` -------------------------------- ### Full Worker Example with KV Operations (TypeScript) Source: https://developers.cloudflare.com/kv/get-started/index A complete TypeScript Worker script demonstrating how to put and get data from a KV namespace, including type safety and error handling. ```typescript export interface Env { USERS_NOTIFICATION_CONFIG: KVNamespace; } export default { async fetch(request, env, ctx): Promise { 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; ``` -------------------------------- ### Sample HTML file content Source: https://developers.cloudflare.com/kv/llms-full.txt A basic HTML file used as a static asset example. ```html Hello World! ``` -------------------------------- ### cURL Examples for Workers KV REST API (PUT and GET) Source: https://developers.cloudflare.com/kv/index Illustrates how to use cURL to interact with the Workers KV REST API for writing (PUT) and reading (GET) key-value pairs. Replace placeholders like $ACCOUNT_ID, $NAMESPACE_ID, $KEY_NAME, $CLOUDFLARE_EMAIL, and $CLOUDFLARE_API_KEY with your actual values. ```bash curl https://api.cloudflare.com/client/v4/accounts/$ACCOUNT_ID/storage/kv/namespaces/$NAMESPACE_ID/values/$KEY_NAME \ -X PUT \ -H 'Content-Type: multipart/form-data' \ -H "X-Auth-Email: $CLOUDFLARE_EMAIL" \ -H "X-Auth-Key: $CLOUDFLARE_API_KEY" \ -d '{ "value": "Some Value" }' curl https://api.cloudflare.com/client/v4/accounts/$ACCOUNT_ID/storage/kv/namespaces/$NAMESPACE_ID/values/$KEY_NAME \ -H "X-Auth-Email: $CLOUDFLARE_EMAIL" \ -H "X-Auth-Key: $CLOUDFLARE_API_KEY" ``` -------------------------------- ### Cloudflare KV Bulk Write Response Example Source: https://developers.cloudflare.com/api/resources/kv/index This is an example of a successful response when writing multiple key-value pairs in bulk to a KV namespace. ```json { "errors": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "messages": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "success": true, "result": { "successful_key_count": 100, "unsuccessful_keys": [ "string" ] } } ``` -------------------------------- ### TypeScript Examples for Workers KV REST API Source: https://developers.cloudflare.com/kv/index Shows how to use the Cloudflare SDK for TypeScript to perform update, get, delete, and list operations on Workers KV namespaces. Ensure you have the Cloudflare SDK installed and your API credentials configured in environment variables. ```typescript const client = new Cloudflare({ apiEmail: process.env['CLOUDFLARE_EMAIL'], // This is the default and can be omitted apiKey: process.env['CLOUDFLARE_API_KEY'], // This is the default and can be omitted }); const value = await client.kv.namespaces.values.update('', 'KEY', { account_id: '', value: 'VALUE', }); const value = await client.kv.namespaces.values.get('', 'KEY', { account_id: '', }); const value = await client.kv.namespaces.values.delete('', 'KEY', { account_id: '', }); // Automatically fetches more pages as needed. for await (const namespace of client.kv.namespaces.list({ account_id: '' })) { console.log(namespace.id); } ``` -------------------------------- ### Wrangler KV command syntax Source: https://developers.cloudflare.com/kv/reference/kv-commands/index Examples of the current kv ... syntax compared to the deprecated kv:... syntax. ```bash wrangler kv namespace list wrangler kv key get wrangler kv bulk put ``` ```bash wrangler kv:namespace list wrangler kv:key get wrangler kv:bulk put ``` -------------------------------- ### List keys response structure Source: https://developers.cloudflare.com/kv/api/list-keys/index Example of the object structure returned by the list() method. ```json { "keys": [ { "name": "foo", "expiration": 1234, "metadata": { "someMetadataKey": "someMetadataValue" } } ], "list_complete": false, "cursor": "6Ck1la0VxJ0djhidm1MdX2FyD" } ``` -------------------------------- ### Worker fetch handler with KV operations Source: https://developers.cloudflare.com/kv/llms-full.txt A complete example showing how to read single/multiple keys and metadata within a Worker fetch handler. ```javascript export default { async fetch(request, env, ctx) { try { // Read single key, returns value or null const value = await env.NAMESPACE.get("first-key"); // Read multiple keys, returns Map of values const values = await env.NAMESPACE.get(["first-key", "second-key"]); // Read single key with metadata, returns value or null const valueWithMetadata = await env.NAMESPACE.getWithMetadata("first-key"); // Read multiple keys with metadata, returns Map of values const valuesWithMetadata = await env.NAMESPACE.getWithMetadata(["first-key", "second-key"]); return new Response({ value: value, values: Object.fromEntries(values), valueWithMetadata: valueWithMetadata, valuesWithMetadata: Object.fromEntries(valuesWithMetadata) }); } catch (e) { return new Response(e.message, { status: 500 }); } }, }; ``` -------------------------------- ### GET /list Source: https://developers.cloudflare.com/kv/llms-full.txt Retrieves a list of keys from the KV namespace. Supports filtering by prefix and pagination using cursors. ```APIDOC ## GET /list ### Description Retrieves a list of keys from the KV namespace. The keys are returned in lexicographically sorted order. ### Parameters #### Query Parameters - **prefix** (string) - Optional - Filter keys that start with this prefix. - **cursor** (string) - Optional - Used for pagination to fetch the next batch of keys. ### Response #### Success Response (200) - **keys** (array) - An array of objects containing name, expiration (optional), and metadata (optional). - **list_complete** (boolean) - Indicates if there are more keys to fetch. - **cursor** (string) - A token used for paginating subsequent requests. #### Response Example { "keys": [ { "name": "foo", "expiration": 1234, "metadata": { "someMetadataKey": "someMetadataValue" } } ], "list_complete": false, "cursor": "6Ck1la0VxJ0djhidm1MdX2FyD" } ``` -------------------------------- ### Request multiple keys with get() Source: https://developers.cloudflare.com/kv/api/read-key-value-pairs/index Syntax for requesting multiple keys using an array, with optional type or cache configuration. ```javascript env.NAMESPACE.get(keys, type?); // OR env.NAMESPACE.get(keys, options?); ``` -------------------------------- ### Request a single key with get() Source: https://developers.cloudflare.com/kv/api/read-key-value-pairs/index Syntax for requesting a single key with optional type or cache configuration. ```javascript env.NAMESPACE.get(key, type?); // OR env.NAMESPACE.get(key, options?); ``` -------------------------------- ### Example Response for Listing Namespaces Source: https://developers.cloudflare.com/api/resources/kv/index This JSON structure represents a successful response when listing KV namespaces, including namespace details and pagination information. ```json { "errors": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "messages": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "success": true, "result": [ { "id": "0f2ac74b498b48028cb68387c421e279", "title": "My Own Namespace", "supports_url_encoding": true } ], "result_info": { "count": 1, "page": 1, "per_page": 20, "total_count": 2000 } } ``` -------------------------------- ### Worker KV write example Source: https://developers.cloudflare.com/kv/api/write-key-value-pairs/index A practical implementation of writing a key-value pair within a Cloudflare Worker fetch handler. ```javascript export default { async fetch(request, env, ctx) { try { await env.NAMESPACE.put("first-key", "This is the value for the key"); return new Response("Successful write", { status: 201, }); } catch (e) { return new Response(e.message, { status: 500 }); } }, }; ``` -------------------------------- ### Fetch keys within a Worker handler Source: https://developers.cloudflare.com/kv/api/list-keys/index Example implementation of listing keys and returning them as a JSON response within a Worker fetch handler. ```javascript export default { async fetch(request, env, ctx) { try { const value = await env.NAMESPACE.list(); return new Response(JSON.stringify(value.keys), { status: 200 }); } catch (e) { return new Response(e.message, {status: 500}); } }, }; ``` -------------------------------- ### Get Value from KV Namespace Source: https://developers.cloudflare.com/kv/get-started/index Use the get() method on the KVNamespace object to retrieve the value associated with a specific key. This example fetches the value for 'user_2'. ```typescript let value = await env.USERS_NOTIFICATION_CONFIG.get("user_2"); ``` -------------------------------- ### Bulk Get Success Response Source: https://developers.cloudflare.com/api/resources/kv/index Example JSON response body returned after a successful bulk retrieval of KV pairs. ```json { "errors": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "messages": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "success": true, "result": { "values": { "key1": "value1", "key2": "value2" } } } ``` -------------------------------- ### Create Cloudflare Worker Project with npm Source: https://developers.cloudflare.com/kv/get-started/index Use this command to initialize a new Cloudflare Worker project named 'kv-tutorial' with npm. ```bash npm create cloudflare@latest -- kv-tutorial ``` -------------------------------- ### PostgreSQL schema and sample data Source: https://developers.cloudflare.com/kv/examples/distributed-configuration-with-workers-kv/index SQL script to create the users table and populate it with sample data for the sync process. ```sql -- Create users table with preview_features_enabled flag CREATE TABLE users ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), username VARCHAR(100) NOT NULL, email VARCHAR(255) NOT NULL, preview_features_enabled BOOLEAN DEFAULT false ); -- Insert sample users INSERT INTO users (username, email, preview_features_enabled) VALUES ('alice', 'alice@example.com', true), ('bob', 'bob@example.com', false), ('charlie', 'charlie@example.com', true); ``` -------------------------------- ### Retrieve Multiple KV Pairs via cURL Source: https://developers.cloudflare.com/api/resources/kv/index Example request to fetch up to 100 KV pairs from a specified namespace using the bulk get endpoint. ```http curl https://api.cloudflare.com/client/v4/accounts/$ACCOUNT_ID/storage/kv/namespaces/$NAMESPACE_ID/bulk/get \ -H 'Content-Type: application/json' \ -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \ -d '{ "keys": [ "My-Key" ] }' ``` -------------------------------- ### Read KV keys in a Worker fetch handler Source: https://developers.cloudflare.com/kv/api/read-key-value-pairs/index Example of using get() and getWithMetadata() within a Cloudflare Worker fetch handler to retrieve values and metadata. ```javascript export default { async fetch(request, env, ctx) { try { // Read single key, returns value or null const value = await env.NAMESPACE.get("first-key"); // Read multiple keys, returns Map of values const values = await env.NAMESPACE.get(["first-key", "second-key"]); // Read single key with metadata, returns value or null const valueWithMetadata = await env.NAMESPACE.getWithMetadata("first-key"); // Read multiple keys with metadata, returns Map of values const valuesWithMetadata = await env.NAMESPACE.getWithMetadata(["first-key", "second-key"]); return new Response({ value: value, values: Object.fromEntries(values), valueWithMetadata: valueWithMetadata, valuesWithMetadata: Object.fromEntries(valuesWithMetadata) }); } catch (e) { return new Response(e.message, { status: 500 }); } }, }; ``` -------------------------------- ### Navigate to Worker Project Directory Source: https://developers.cloudflare.com/kv/get-started/index Change into the newly created directory for your Worker project. ```bash cd kv-tutorial ``` -------------------------------- ### Create Cloudflare Worker Project with pnpm Source: https://developers.cloudflare.com/kv/get-started/index Use this command to initialize a new Cloudflare Worker project named 'kv-tutorial' with pnpm. ```bash pnpm create cloudflare@latest kv-tutorial ``` -------------------------------- ### Create Cloudflare Worker Project with yarn Source: https://developers.cloudflare.com/kv/get-started/index Use this command to initialize a new Cloudflare Worker project named 'kv-tutorial' with yarn. ```bash yarn create cloudflare kv-tutorial ``` -------------------------------- ### Initialize a new Worker project Source: https://developers.cloudflare.com/kv/llms-full.txt Commands to create a new Cloudflare Worker project using different package managers. ```bash npm create cloudflare@latest -- kv-tutorial ``` ```bash yarn create cloudflare kv-tutorial ``` ```bash pnpm create cloudflare@latest kv-tutorial ``` -------------------------------- ### Get KV Key Value as Text with Wrangler Source: https://developers.cloudflare.com/kv/get-started/index To view the value directly as plain text in your terminal, append the `--text` flag to the `get` command. This is useful for quickly inspecting string values. ```bash npx wrangler kv key get --binding=USERS_NOTIFICATION_CONFIG "user_1" --text ``` -------------------------------- ### Environment configuration for sync script Source: https://developers.cloudflare.com/kv/examples/distributed-configuration-with-workers-kv/index Required environment variables for connecting to the database and authenticating with Cloudflare. ```text DATABASE_CONNECTION_STRING = CLOUDFLARE_EMAIL = CLOUDFLARE_API_KEY = CLOUDFLARE_ACCOUNT_ID = CLOUDFLARE_WORKERS_KV_NAMESPACE_ID = ``` -------------------------------- ### GET Key-Value Pair using cURL Source: https://developers.cloudflare.com/kv/llms-full.txt Uses cURL to perform a GET request to the Cloudflare API to retrieve a value associated with a specific key from a KV namespace. Replace placeholders with your account ID, namespace ID, and API credentials. ```bash curl https://api.cloudflare.com/client/v4/accounts/$ACCOUNT_ID/storage/kv/namespaces/$NAMESPACE_ID/values/$KEY_NAME \ -H "X-Auth-Email: $CLOUDFLARE_EMAIL" \ -H "X-Auth-Key: $CLOUDFLARE_API_KEY" ``` -------------------------------- ### List KV namespace keys Source: https://developers.cloudflare.com/kv/reference/kv-commands/index Use these commands to output a list of all keys present in a given KV namespace. ```bash npx wrangler kv key list ``` ```bash pnpm wrangler kv key list ``` ```bash yarn wrangler kv key list ``` -------------------------------- ### GET Multiple Keys Source: https://developers.cloudflare.com/kv/llms-full.txt Retrieves values for multiple keys from a KV namespace. ```APIDOC ## GET env.NAMESPACE.get(keys) ### Description Retrieves the values for a list of keys from a KV namespace. Note that this method does not support arrayBuffer or stream return types. ### Parameters #### Request Body - **keys** (string[]) - Required - The keys of the KV pairs. Max: 100 keys. - **type** (string) - Optional - The type of the value to be returned: "text" (default) or "json". - **options** (object) - Optional - Object containing cacheTtl (number) and type (string). ### Response #### Success Response (200) - **response** (Promise>) - A map of keys to their values. If no key is found, null is returned for that key. ``` -------------------------------- ### Create a KV namespace Source: https://developers.cloudflare.com/kv/reference/kv-commands/index Creates a new KV namespace using the specified package manager. ```bash npx wrangler kv namespace create [NAMESPACE] ``` ```bash pnpm wrangler kv namespace create [NAMESPACE] ``` ```bash yarn wrangler kv namespace create [NAMESPACE] ``` -------------------------------- ### Get a Namespace Source: https://developers.cloudflare.com/api/resources/kv/index Retrieves details for a specific KV namespace using its ID. ```APIDOC ## GET /accounts/{account_id}/storage/kv/namespaces/{namespace_id} ### Description Get the namespace corresponding to the given ID. ### Method GET ### Endpoint `/accounts/{account_id}/storage/kv/namespaces/{namespace_id}` ### Parameters #### Path Parameters - **account_id** (string) - Optional - Identifier. - **namespace_id** (string) - Required - Namespace identifier tag. ### Response #### Success Response (200) - **errors** (array of ResponseInfo) - Description of errors encountered. - **messages** (array of ResponseInfo) - Description of messages encountered. - **success** (boolean) - Whether the API call was successful. - **result** (Namespace) - The KV namespace object. - **id** (string) - Namespace identifier tag. - **title** (string) - A human-readable string name for a Namespace. - **supports_url_encoding** (boolean) - Optional - True if keys written on the URL will be URL-decoded before storing. ### Request Example ```http curl https://api.cloudflare.com/client/v4/accounts/$ACCOUNT_ID/storage/kv/namespaces/$NAMESPACE_ID \ -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" ``` ### Response Example ```json { "errors": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "messages": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "success": true, "result": { "id": "0f2ac74b498b48028cb68387c421e279", "title": "My Own Namespace", "supports_url_encoding": true } } ``` ``` -------------------------------- ### kv key get Source: https://developers.cloudflare.com/kv/llms-full.txt Retrieves the value associated with a specific key from a KV namespace. ```APIDOC ## wrangler kv key get [KEY] ### Description Read a single value by key from the given namespace. ### Parameters #### Path Parameters - **KEY** (string) - Required - The key value to get. #### Query Parameters - **--text** (boolean) - Optional - Decode the returned value as a utf8 string - **--binding** (string) - Optional - The binding name to the namespace to get from - **--namespace-id** (string) - Optional - The id of the namespace to get from - **--preview** (boolean) - Optional - Interact with a preview namespace - **--local** (boolean) - Optional - Interact with local storage - **--remote** (boolean) - Optional - Interact with remote storage - **--persist-to** (string) - Optional - Directory for local persistence ``` -------------------------------- ### GET Single Key with Metadata Source: https://developers.cloudflare.com/kv/llms-full.txt Retrieves a single value along with its associated metadata. ```APIDOC ## GET env.NAMESPACE.getWithMetadata(key) ### Description Retrieves the value and metadata for a single key from a KV namespace. ### Parameters #### Path Parameters - **key** (string) - Required - The key of the KV pair. #### Query Parameters - **type** (string) - Optional - The type of the value: "text", "json", "arrayBuffer", or "stream". - **options** (object) - Optional - Object containing cacheTtl (number) and type (string). ### Response #### Success Response (200) - **response** (Promise<{ value: any, metadata: string | null }>) - An object containing the value and the metadata. If no metadata exists, null is returned. ``` -------------------------------- ### GET /getWithMetadata Source: https://developers.cloudflare.com/kv/api/read-key-value-pairs/index Retrieves a value and its associated metadata for a specific key from the KV store. ```APIDOC ## GET /getWithMetadata ### Description Retrieves the value and metadata for a requested key. The response includes the value (formatted based on the type parameter) and metadata. ### Parameters #### Query Parameters - **type** (string) - Optional - The format of the returned value: 'text' (default), 'json', 'stream', or 'arrayBuffer'. - **cacheTtl** (integer) - Optional - Time in seconds to cache the result at the edge. Must be >= 30. Default is 60. ### Response #### Success Response (200) - **value** (string|Object) - The stored value. - **metadata** (string|Object|null) - The associated metadata, or null if none exists. ### Error Handling - **413 Error**: Returned if the response size exceeds the 25 MB limit. ``` -------------------------------- ### List KV namespaces Source: https://developers.cloudflare.com/kv/reference/kv-commands/index Lists all KV namespaces associated with the account ID. ```bash npx wrangler kv namespace list ``` ```bash pnpm wrangler kv namespace list ``` ```bash yarn wrangler kv namespace list ``` -------------------------------- ### KV list() Response Structure Source: https://developers.cloudflare.com/kv/llms-full.txt Example of the JSON object returned by the list() method. ```json { "keys": [ { "name": "foo", "expiration": 1234, "metadata": { "someMetadataKey": "someMetadataValue" } } ], "list_complete": false, "cursor": "6Ck1la0VxJ0djhidm1MdX2FyD" } ``` -------------------------------- ### Get Metadata for a Key Source: https://developers.cloudflare.com/kv/llms-full.txt Retrieves metadata associated with a specific key in a Cloudflare KV namespace. ```APIDOC ## GET /accounts/{account_id}/storage/kv/namespaces/{namespace_id}/metadata/{key_name} ### Description Retrieves metadata associated with a specific key in a Cloudflare KV namespace. ### Method GET ### Endpoint /accounts/{account_id}/storage/kv/namespaces/{namespace_id}/metadata/{key_name} ### Parameters #### Path Parameters - **account_id** (string) - Optional - Identifier. - **namespace_id** (string) - Required - Namespace identifier tag. - **key_name** (string) - Required - A key's name. The name may be at most 512 bytes. All printable, non-whitespace characters are valid. Use percent-encoding to define key names as part of a URL. ### Response #### Success Response (200) - **errors** (array of ResponseInfo) - List of errors encountered. - **messages** (array of ResponseInfo) - List of informational messages. - **success** (boolean) - Whether the API call was successful. - **result** (unknown) - Arbitrary JSON that is associated with a key. #### Response Example ```json { "errors": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "messages": [ { "code": 1000, "message": "message", "documentation_url": "documentation_url", "source": { "pointer": "pointer" } } ], "success": true, "result": {} } ``` ``` -------------------------------- ### Create HTML file for KV storage Source: https://developers.cloudflare.com/kv/examples/workers-kv-to-serve-assets/index This is a sample HTML file to be stored as a static asset in Workers KV. Ensure the content adheres to KV value size limits. ```html Hello World!

Hello World!

``` -------------------------------- ### Get KV Key Source: https://developers.cloudflare.com/kv/reference/kv-commands/index Reads a single value by key from a specified Workers KV namespace. ```APIDOC ## GET /kv/key ### Description Reads a single value by key from the given namespace. ### Method GET ### Endpoint `/kv/key` ### Parameters #### Path Parameters - **KEY** (string) - Required - The key value to get. #### Query Parameters - **--text** (boolean) - Optional - Decode the returned value as a utf8 string. Default: false - **--binding** (string) - Optional - The binding name to the namespace to get from - **--namespace-id** (string) - Optional - The id of the namespace to get from - **--preview** (boolean) - Optional - Interact with a preview namespace. Default: false - **--local** (boolean) - Optional - Interact with local storage - **--remote** (boolean) - Optional - Interact with remote storage - **--persist-to** (string) - Optional - Directory for local persistence ### Request Example ```json { "example": "npx wrangler kv key get myKey --text --binding myNamespace" } ``` ### Response #### Success Response (200) - **value** (string) - The value associated with the key. - **type** (string) - The type of the value (e.g., 'text', 'json', 'arraybuffer'). #### Response Example ```json { "example": "{\"value\": \"some_value\", \"type\": \"text\"}" } ``` ``` -------------------------------- ### POST /accounts/{account_id}/storage/kv/namespaces Source: https://developers.cloudflare.com/api/resources/kv/index Creates a new KV namespace. ```APIDOC ## POST /accounts/{account_id}/storage/kv/namespaces ### Description Creates a new KV namespace. ### Method POST ### Endpoint /accounts/{account_id}/storage/kv/namespaces ### Request Body - **title** (string) - Required - A human-readable string name for a Namespace. ### Request Example { "title": "My Own Namespace" } ### Response #### Success Response (200) - **id** (string) - Namespace identifier tag. - **title** (string) - A human-readable string name for a Namespace. - **supports_url_encoding** (boolean) - True if keys written on the URL will be URL-decoded before storing. #### Response Example { "success": true, "result": { "id": "0f2ac74b498b48028cb68387c421e279", "title": "My Own Namespace", "supports_url_encoding": true } } ``` -------------------------------- ### KV Namespace List Keys (REST API) Source: https://developers.cloudflare.com/kv/llms-full.txt You can list keys on the command line with Wrangler or with the REST API. ```APIDOC ## GET /namespaces/:namespace_id/keys ### Description Lists all keys within a KV namespace. ### Method GET ### Endpoint /namespaces/:namespace_id/keys ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of keys to return. - **prefix** (string) - Optional - A prefix to filter keys by. - **cursor** (string) - Optional - A cursor for pagination. ### Response #### Success Response (200) - **keys** (array) - An array of key objects, each containing 'name' and 'expiration' properties. - **list_complete** (boolean) - Indicates if the entire list has been returned. - **cursor** (string) - A cursor for the next page of results. #### Response Example ```json { "keys": [ { "name": "example-key", "expiration": 1678886400 } ], "list_complete": true, "cursor": null } ``` ``` -------------------------------- ### Bulk Get Keys Source: https://developers.cloudflare.com/kv/llms-full.txt Retrieves multiple keys from a KV namespace. Supports retrieving values only or values with metadata. ```APIDOC ## POST /accounts/$ACCOUNT_ID/storage/kv/namespaces/$NAMESPACE_ID/bulk/get ### Description Retrieves multiple keys from a KV namespace. You can optionally include metadata in the response. ### Method POST ### Endpoint `/accounts/$ACCOUNT_ID/storage/kv/namespaces/$NAMESPACE_ID/bulk/get` ### Parameters #### Request Body - **keys** (array of string) - Required - Array of keys to retrieve (maximum of 100). - **type** (string) - Optional - Whether to parse JSON values in the response. Can be `"text"` or `"json"`. - **withMetadata** (boolean) - Optional - Whether to include metadata in the response. ### Request Example ```json { "keys": [ "My-Key-1", "My-Key-2" ], "withMetadata": true } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the API call was successful. - **result** (object) - Contains the retrieved key-value pairs. The structure depends on the `withMetadata` parameter. - **values** (map) - If `withMetadata` is false, this map contains keys paired with their string, number, boolean, or unknown map values. - **values** (map) - If `withMetadata` is true, this map contains keys paired with objects containing `metadata`, `value`, and an optional `expiration`. - **errors** (array of ResponseInfo) - Information about any errors encountered. - **messages** (array of ResponseInfo) - Information about any messages generated during the process. #### Response Example ```json { "errors": [], "messages": [], "success": true, "result": { "values": { "My-Key-1": { "metadata": {}, "value": "some-value", "expiration": 1678886400 }, "My-Key-2": { "metadata": {}, "value": {"nested": "json"} } } } } ``` ``` -------------------------------- ### Upload KV Entry via Wrangler CLI Source: https://developers.cloudflare.com/kv/examples/workers-kv-to-serve-assets/index Use the Wrangler CLI to upload a local file as a KV entry. Replace `` with your actual KV namespace ID. ```bash npx wrangler kv key put hello-world.json --path hello-world.json --namespace-id= ``` -------------------------------- ### Store value in metadata Source: https://developers.cloudflare.com/kv/api/list-keys/index Efficiently store values in metadata using put() to avoid subsequent get() calls. ```javascript await NAMESPACE.put(key, "", { metadata: { value: value }, }); ``` -------------------------------- ### kv bulk get Source: https://developers.cloudflare.com/kv/llms-full.txt Retrieves multiple key-value pairs from a Workers KV namespace by specifying a file containing the keys. ```APIDOC ## `kv bulk get` Gets multiple key-value pairs from a namespace. ### Method GET ### Endpoint `kv bulk get [FILENAME]` ### Parameters #### Path Parameters - **[FILENAME]** (string) - Required - The file containing the keys to get. #### Query Parameters - **--binding** (string) - Optional - The binding name to the namespace to get from. - **--namespace-id** (string) - Optional - The id of the namespace to get from. - **--preview** (boolean) - Optional - Interact with a preview namespace. Default: false. - **--local** (boolean) - Optional - Interact with local storage. - **--remote** (boolean) - Optional - Interact with remote storage. - **--persist-to** (string) - Optional - Directory for local persistence. #### Global Flags - **--v** (boolean) - Optional - Alias: --version - Show version number. - **--cwd** (string) - Optional - Run as if Wrangler was started in the specified directory instead of the current working directory. - **--config** (string) - Optional - Alias: --c - Path to Wrangler configuration file. - **--env** (string) - Optional - Alias: --e - Environment to use for operations, and for selecting .env and .dev.vars files. - **--env-file** (string) - Optional - Path to an .env file to load - can be specified multiple times - values from earlier files are overridden by values in later files. - **--experimental-provision** (boolean) - Optional - Experimental: Enable automatic resource provisioning. Aliases: --x-provision. Default: true. - **--experimental-auto-create** (boolean) - Optional - Automatically provision draft bindings with new resources. Alias: --x-auto-create. Default: true. ### Request Example ```bash npx wrangler kv bulk get keys.txt --binding my_namespace ``` ### Response (Response format depends on the content of the keys. Typically a JSON object where keys are mapped to their values.) #### Success Response (200) - **key** (string) - The key retrieved. - **value** (string) - The value associated with the key. #### Response Example ```json { "key1": "value1", "key2": "value2" } ``` ``` -------------------------------- ### Configure environment-specific routes and namespaces Source: https://developers.cloudflare.com/kv/llms-full.txt Define environment-specific settings including routes and KV namespaces in Wrangler configuration. ```json { "$schema": "./node_modules/wrangler/config-schema.json", "type": "webpack", "name": "my-worker", "account_id": "", "route": "staging.example.com/*", "workers_dev": false, "kv_namespaces": [ { "binding": "MY_KV", "id": "06779da6940b431db6e566b4846d64db" } ], "env": { "production": { "route": "example.com/*", "kv_namespaces": [ { "binding": "MY_KV", "id": "07bc1f3d1f2a4fd8a45a7e026e2681c6" } ] } } } ``` ```toml "$schema" = "./node_modules/wrangler/config-schema.json" type = "webpack" name = "my-worker" account_id = "" route = "staging.example.com/*" workers_dev = false [[kv_namespaces]] binding = "MY_KV" id = "06779da6940b431db6e566b4846d64db" [env.production] route = "example.com/*" [[env.production.kv_namespaces]] binding = "MY_KV" id = "07bc1f3d1f2a4fd8a45a7e026e2681c6" ``` -------------------------------- ### Demonstrate KV write rate limiting Source: https://developers.cloudflare.com/kv/api/write-key-value-pairs/index This example forces concurrent writes to a single key to demonstrate how 429 Too Many Requests errors occur. It is intended for demonstration purposes only and should not be used in production. ```TypeScript export default { async fetch(request, env, ctx): Promise { // Rest of code omitted const key = "common-key"; const parallelWritesCount = 20; // Helper function to attempt a write to KV and handle errors const attemptWrite = async (i: number) => { try { await env.YOUR_KV_NAMESPACE.put(key, `Write attempt #${i}`); return { attempt: i, success: true }; } catch (error) { // An error may be thrown if a write to the same key is made within 1 second with a message. For example: // error: { // "message": "KV PUT failed: 429 Too Many Requests" // } return { attempt: i, success: false, error: { message: (error as Error).message }, }; } }; // Send all requests in parallel and collect results const results = await Promise.all( Array.from({ length: parallelWritesCount }, (_, i) => attemptWrite(i + 1), ), ); // Results will look like: // [ // { // "attempt": 1, // "success": true // }, // { // "attempt": 2, // "success": false, // "error": { // "message": "KV PUT failed: 429 Too Many Requests" // } // }, // ... // ] return new Response(JSON.stringify(results), { headers: { "Content-Type": "application/json" }, }); }, }; ```