-
Notifications
You must be signed in to change notification settings - Fork 10.2k
thomasgauvin: add examples to workers kv #20655
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
thomasgauvin
merged 10 commits into
production
from
thomasgauvin-add-workers-kv-examples
Mar 27, 2025
Merged
Changes from 3 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
78e6c00
thomasgauvin: add examples to workers kv
thomasgauvin 7974715
Apply suggestions from code review
Oxyjun c28e164
Update src/content/docs/kv/examples/routing-with-workers-kv.mdx
Oxyjun e7dd115
Update src/content/docs/kv/examples/distributed-configuration-with-wo…
thomasgauvin 3bee719
Merge branch 'production' into thomasgauvin-add-workers-kv-examples
thomasgauvin 96d44bc
thomasgauvin: update caching with kv vs cache api
thomasgauvin bff8da0
Update src/content/docs/kv/examples/cache-data-with-workers-kv.mdx
thomasgauvin da0fa4b
Update src/content/docs/kv/examples/cache-data-with-workers-kv.mdx
thomasgauvin 2dde10e
Update src/content/docs/kv/examples/cache-data-with-workers-kv.mdx
thomasgauvin c222fff
Merge branch 'production' into thomasgauvin-add-workers-kv-examples
thomasgauvin File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
134 changes: 134 additions & 0 deletions
134
src/content/docs/kv/examples/cache-data-with-workers-kv.mdx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,134 @@ | ||
| --- | ||
| type: example | ||
| summary: Cache data or API responses in Workers KV to improve application performance | ||
| tags: | ||
| - KV | ||
| pcx_content_type: configuration | ||
| title: Cache data with Workers KV | ||
| sidebar: | ||
| order: 5 | ||
| description: Example of how to use Workers KV to build a distributed application configuration store. | ||
| --- | ||
|
|
||
| import { Render, PackageManagers, Tabs, TabItem } from "~/components"; | ||
|
|
||
| Workers KV can be used as a persistent, single, global cache accessible from Cloudflare Workers to speed up your application. | ||
| Data cached in Workers KV is accessible from all other Cloudflare locations as well, and persists until expiry or deletion. | ||
|
|
||
| After fetching data from external resources in your Workers application, you can write the data to Workers KV. | ||
| On subsequent Worker requests (in the same region or in other regions), you can read the cached data from Workers KV instead of calling the external API. | ||
| This improves your Worker application's performance and resilience while reducing load on external resources. | ||
|
|
||
| This example shows how you can cache data in Workers KV and read cached data from Workers KV in a Worker application. | ||
|
|
||
| ## Cache data in Workers KV from your Worker application | ||
|
|
||
| In the following `index.ts` file, the Worker fetches data from an external server and caches the response in Workers KV. If the data is already cached in Workers KV, the Worker reads the cached data from Workers KV instead of calling the external API. | ||
|
|
||
| <Tabs> | ||
| <TabItem label="index.ts"> | ||
| ```js title="index.ts" collapse={42-1000} | ||
| interface Env { | ||
| CACHE_KV: KVNamespace; | ||
| } | ||
|
|
||
| export default { | ||
| async fetch(request, env, ctx): Promise<Response> { | ||
|
|
||
| const EXPIRATION_TTL = 60; // Cache expiration in seconds | ||
| const url = 'https://example.com'; | ||
| const cacheKey = "cache-json-example"; | ||
|
|
||
| // Try to get data from KV cache first | ||
| let data = await env.CACHE_KV.get(cacheKey, { type: 'json' }); | ||
| let fromCache = true; | ||
|
|
||
| // If data is not in cache, fetch it from example.com | ||
| if (!data) { | ||
| console.log('Cache miss. Fetching fresh data from example.com'); | ||
| fromCache = false; | ||
|
|
||
| // In this example, we are fetching HTML content but it can also be API responses or any other data | ||
| const response = await fetch(url); | ||
| const htmlData = await response.text(); | ||
|
|
||
| // In this example, we are converting HTML to JSON to demonstrate caching JSON data with Workers KV | ||
| // You could cache any type of data, or even cache the HTML data directly | ||
| data = helperConvertToJSON(htmlData); | ||
| // The expirationTtl option is used to set the expiration time for the cache entry (in seconds), otherwise it will be stored indefinitely | ||
| await env.CACHE_KV.put(cacheKey, JSON.stringify(data), { expirationTtl: EXPIRATION_TTL }); | ||
| } | ||
|
|
||
| // Return the appropriate response format | ||
| return new Response(JSON.stringify({ | ||
| data, | ||
| fromCache | ||
| }), { | ||
| headers: { 'Content-Type': 'application/json' } | ||
| }); | ||
|
|
||
| } | ||
| } satisfies ExportedHandler<Env>; | ||
|
|
||
| // Helper function to convert HTML to JSON | ||
| function helperConvertToJSON(html: string) { | ||
| // Parse HTML and extract relevant data | ||
| const title = helperExtractTitle(html); | ||
| const content = helperExtractContent(html); | ||
| const lastUpdated = new Date().toISOString(); | ||
|
|
||
| return { title, content, lastUpdated }; | ||
| } | ||
|
|
||
| // Helper function to extract title from HTML | ||
| function helperExtractTitle(html: string) { | ||
| const titleMatch = html.match(/<title>(.\*?)<\/title>/i); | ||
| return titleMatch ? titleMatch[1] : 'No title found'; | ||
| } | ||
|
|
||
| // Helper function to extract content from HTML | ||
| function helperExtractContent(html: string) { | ||
| const bodyMatch = html.match(/<body>(.\*?)<\/body>/is); | ||
| if (!bodyMatch) return 'No content found'; | ||
|
|
||
| // Strip HTML tags for a simple text representation | ||
| const textContent = bodyMatch[1].replace(/<[^>]*>/g, ' ') | ||
| .replace(/\s+/g, ' ') | ||
| .trim(); | ||
|
|
||
| return textContent; | ||
| } | ||
|
|
||
| ``` | ||
| </TabItem> | ||
| <TabItem label="wrangler.jsonc"> | ||
| ```json | ||
| { | ||
| "$schema": "node_modules/wrangler/config-schema.json", | ||
| "name": "<ENTER_WORKER_NAME>", | ||
| "main": "src/index.ts", | ||
| "compatibility_date": "2025-03-03", | ||
| "observability": { | ||
| "enabled": true | ||
| }, | ||
| "kv_namespaces": [ | ||
| { | ||
| "binding": "CACHE_KV", | ||
| "id": "<YOUR_BINDING_ID>" | ||
| } | ||
| ] | ||
| } | ||
| ``` | ||
| </TabItem> | ||
| </Tabs> | ||
|
|
||
| This code snippet demonstrates how to read and update cached data in Workers KV from your Worker. | ||
| If the data is not in the Workers KV cache, the Worker fetches the data from an external server and caches it in Workers KV. | ||
|
|
||
| In this example, we convert HTML to JSON to demonstrate how to cache JSON data with Workers KV, but any type of data | ||
| can be cached in Workers KV. For instance, you could cache API responses, HTML content, or any other data that you want to persist across requests. | ||
|
|
||
| ## Related resources | ||
|
|
||
| - [Rust support in Workers](/workers/languages/rust/). | ||
| - [Using KV in Workers](/kv/get-started/). |
235 changes: 235 additions & 0 deletions
235
src/content/docs/kv/examples/distributed-configuration-with-workers-kv.mdx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,235 @@ | ||
| --- | ||
| type: example | ||
| summary: Use Workers KV to as a geo-distributed, low-latency configuration store for your Workers application | ||
| tags: | ||
| - KV | ||
| pcx_content_type: configuration | ||
| title: Build a distributed configuration store | ||
| sidebar: | ||
| order: 5 | ||
| description: Example of how to use Workers KV to build a distributed application configuration store. | ||
| --- | ||
|
|
||
| import { Render, PackageManagers, Tabs, TabItem } from "~/components"; | ||
|
|
||
| Storing application configuration data is an ideal use case for Workers KV. Configuration data can include data to personalize an application for each user or tenant, enable features for user groups, restrict access with allow-lists/deny-lists, etc. These use-cases can have high read volumes that are highly cacheable by Workers KV, which can ensure low-latency reads from your Workers application. | ||
|
|
||
| In this example, application configuration data is used to personalize the Workers application for each user. The configuration data is stored in an external application and database, and written to Workers KV using the REST API. | ||
|
|
||
| ## Write your configuration from your external application to Workers KV | ||
|
|
||
| In some cases, your source-of-truth for your configuration data may be stored elsewhere than Workers KV. | ||
| If this is the case, use the Workers KV REST API to write the configuration data to your Workers KV namespace. You may also | ||
thomasgauvin marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| The following external Node.js application demonstrates a simple scripts that reads user data from a database and writes it to Workers KV using the REST API library. | ||
|
|
||
| <Tabs> | ||
| <TabItem label="index.js"> | ||
| ```js title="index.js" | ||
| const postgres = require('postgres'); | ||
| const { Cloudflare } = require('cloudflare'); | ||
| const { backOff } = require('exponential-backoff'); | ||
|
|
||
| if(!process.env.DATABASE_CONNECTION_STRING || !process.env.CLOUDFLARE_EMAIL || !process.env.CLOUDFLARE_API_KEY || !process.env.CLOUDFLARE_WORKERS_KV_NAMESPACE_ID || !process.env.CLOUDFLARE_ACCOUNT_ID) { | ||
| console.error('Missing required environment variables.'); | ||
| process.exit(1); | ||
| } | ||
|
|
||
| // Setup Postgres connection | ||
| const sql = postgres(process.env.DATABASE_CONNECTION_STRING); | ||
|
|
||
| // Setup Cloudflare REST API client | ||
| const client = new Cloudflare({ | ||
| apiEmail: process.env.CLOUDFLARE_EMAIL, | ||
| apiKey: process.env.CLOUDFLARE_API_KEY, | ||
| }); | ||
|
|
||
| // Function to sync Postgres data to Workers KV | ||
| async function syncPreviewStatus() { | ||
| console.log('Starting sync of user preview status...'); | ||
|
|
||
| try { | ||
| // Get all users and their preview status | ||
| const users = await sql`SELECT id, preview_features_enabled FROM users`; | ||
|
|
||
| console.log(users); | ||
|
|
||
| // Create the bulk update body | ||
| const bulkUpdateBody = users.map(user => ({ | ||
| key: user.id, | ||
| value: JSON.stringify({ | ||
| preview_features_enabled: user.preview_features_enabled | ||
| }) | ||
| })); | ||
|
|
||
| const response = await backOff(async () => { | ||
| console.log("trying to update") | ||
| try{ | ||
| const response = await client.kv.namespaces.bulkUpdate(process.env.CLOUDFLARE_WORKERS_KV_NAMESPACE_ID, { | ||
| account_id: process.env.CLOUDFLARE_ACCOUNT_ID, | ||
| body: bulkUpdateBody | ||
| }); | ||
| } | ||
| catch(e){ | ||
| // Implement your error handling and logging here | ||
| console.log(e); | ||
| throw e; // Rethrow the error to retry | ||
| } | ||
| }); | ||
|
|
||
| console.log(`Sync complete. Updated ${users.length} users.`); | ||
| } catch (error) { | ||
| console.error('Error syncing preview status:', error); | ||
| } | ||
| } | ||
|
|
||
| // Run the sync function | ||
| syncPreviewStatus() | ||
| .catch(console.error) | ||
| .finally(() => process.exit(0)); | ||
| ``` | ||
| </TabItem> | ||
| <TabItem label=".env"> | ||
| ```md title=".env" | ||
| DATABASE_CONNECTION_STRING = <DB_CONNECTION_STRING_HERE> | ||
| CLOUDFLARE_EMAIL = <CLOUDFLARE_EMAIL_HERE> | ||
| CLOUDFLARE_API_KEY = <CLOUDFLARE_API_KEY_HERE> | ||
| CLOUDFLARE_ACCOUNT_ID = <CLOUDFLARE_ACCOUNT_ID_HERE> | ||
| CLOUDFLARE_WORKERS_KV_NAMESPACE_ID = <CLOUDFLARE_WORKERS_KV_NAMESPACE_ID_HERE> | ||
| ```` | ||
|
|
||
| </TabItem> | ||
| <TabItem label="db.sql"> | ||
| ```sql title="db.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', '[email protected]', true), | ||
| ('bob', '[email protected]', false), | ||
| ('charlie', '[email protected]', true); | ||
|
|
||
| ```` | ||
| </TabItem> | ||
| </Tabs> | ||
|
|
||
| In this code snippet, the Node.js application reads user data from a Postgres database and writes the user data to be used for configuration in our Workers application to Workers KV using the Cloudflare REST API Node.js library. | ||
| The application also uses exponential backoff to handle retries in case of errors. | ||
|
|
||
| ## Use configuration data from Workers KV in your Worker application | ||
|
|
||
| With the configuration data now in the Workers KV namespace, we can use it in our Workers application to personalize the application for each user. | ||
|
|
||
| <Tabs> | ||
| <TabItem label="index.ts"> | ||
| ```js title="index.ts" | ||
| // Example configuration data stored in Workers KV: | ||
| // Key: "user-id-abc" | Value: {"preview_features_enabled": false} | ||
| // Key: "user-id-def" | Value: {"preview_features_enabled": true} | ||
|
|
||
| interface Env { | ||
| USER_CONFIGURATION: KVNamespace; | ||
| } | ||
|
|
||
| export default { | ||
| async fetch(request, env) { | ||
| // Get user ID from query parameter | ||
| const url = new URL(request.url); | ||
| const userId = url.searchParams.get('userId'); | ||
|
|
||
| if (!userId) { | ||
| return new Response('Please provide a userId query parameter', { | ||
| status: 400, | ||
| headers: { 'Content-Type': 'text/plain' } | ||
| }); | ||
| } | ||
|
|
||
|
|
||
| const userConfiguration = await env.USER_CONFIGURATION.get<{ | ||
| preview_features_enabled: boolean; | ||
| }>(userId, {type: "json"}); | ||
|
|
||
| console.log(userConfiguration); | ||
|
|
||
| // Build HTML response | ||
| const html = ` | ||
| <!DOCTYPE html> | ||
| <html> | ||
| <head> | ||
| <title>My App</title> | ||
| <style> | ||
| body { | ||
| font-family: Arial, sans-serif; | ||
| max-width: 800px; | ||
| margin: 0 auto; | ||
| padding: 20px; | ||
| } | ||
| .preview-banner { | ||
| background-color: #ffeb3b; | ||
| padding: 10px; | ||
| text-align: center; | ||
| margin-bottom: 20px; | ||
| border-radius: 4px; | ||
| } | ||
| </style> | ||
| </head> | ||
| <body> | ||
| ${userConfiguration?.preview_features_enabled ? ` | ||
| <div class="preview-banner"> | ||
| 🎉 You have early access to preview features! 🎉 | ||
| </div> | ||
| ` : ''} | ||
| <h1>Welcome to My App</h1> | ||
| <p>This is the regular content everyone sees.</p> | ||
| </body> | ||
| </html> | ||
| `; | ||
|
|
||
| return new Response(html, { | ||
| headers: { "Content-Type": "text/html; charset=utf-8" } | ||
| }); | ||
| } | ||
| } satisfies ExportedHandler<Env>; | ||
|
|
||
| ``` | ||
| </TabItem> | ||
| <TabItem label="wrangler.jsonc"> | ||
| ```json | ||
| { | ||
| "$schema": "node_modules/wrangler/config-schema.json", | ||
| "name": "<ENTER_WORKER_NAME>", | ||
| "main": "src/index.ts", | ||
| "compatibility_date": "2025-03-03", | ||
| "observability": { | ||
| "enabled": true | ||
| }, | ||
| "kv_namespaces": [ | ||
| { | ||
| "binding": "USER_CONFIGURATION", | ||
| "id": "<YOUR_BINDING_ID>" | ||
| } | ||
| ] | ||
| } | ||
| ```` | ||
|
|
||
| </TabItem> | ||
| </Tabs> | ||
|
|
||
| This code will use the path within the URL and find the file associated to the path within the KV store. It also sets the proper MIME type in the response to inform the browser how to handle the response. To retrieve the value from the KV store, this code uses `arrayBuffer` to properly handle binary data such as images, documents, and video/audio files. | ||
|
|
||
| ## Optimize performance for configuration | ||
|
|
||
| To optimize performance, you may opt to consolidate values in fewer key-value pairs. By doing so, you may benefit from higher caching efficiency and lower latency. | ||
|
|
||
| For example, instead of storing each user's configuration in a separate key-value pair, you may store all users' configurations in a single key-value pair. This approach may be suitable for use-cases where the configuration data is small and can be easily managed in a single key-value pair (the [size limit for a Workers KV value is 25 MiB](/kv/platform/limits/)). | ||
|
|
||
| ## Related resources | ||
|
|
||
| - [Rust support in Workers](/workers/languages/rust/) | ||
| - [Using KV in Workers](/kv/get-started/) | ||
11 changes: 11 additions & 0 deletions
11
src/content/docs/kv/examples/implement-ab-testing-with-workers-kv.mdx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| --- | ||
| type: example | ||
| summary: Use Workers KV to store A/B testing configuration data and analyze the performance of different versions of your website | ||
| tags: | ||
| - KV | ||
| pcx_content_type: configuration | ||
| title: A/B testing with Workers KV | ||
| external_link: /reference-architecture/diagrams/serverless/a-b-testing-using-workers/ | ||
| sidebar: | ||
| order: 6 | ||
| --- |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.