Cloudflare Worker Demo
The code samples below demonstrates how a Cloudflare Worker can accept HTTP requests, store and retrieve data from KV, and respond to the request.
Storing Data in KV
Presenters Link to Sample On Dashboard: Worker Demo on Cloudflare Dashboard
// Cloudflare Workers is a v8 Isolate. So, it has event handlers just
// like a browser does. This listens for any HTTP request and sends it to
// the `handleRequest` function
addEventListener("fetch", (event) => {
event.respondWith(
handleRequest(event.request).catch(
(err) => new Response(err.stack, { status: 500 })
)
);
});
async function handleRequest(request) {
const { pathname } = new URL(request.url);
const greetingString = "/greeting/";
// Route greets a visitor when they pass in their name.
// Ex: https://hello-name-kv-demo.justin-cftemp.workers.dev/greeting/Justin
if (pathname.startsWith(greetingString)) {
const now = Date.now();
// Extract the visitors name or provide a default
const name = pathname.replace(greetingString, "") || "World";
// Keys are always sorted lexigraphically. To get the responses sorted
// in order of visit add the timestamp in front.
// This would NOT be a good way to store keys if you needed to query
// on these keys
const key = `${now}_${name}`;
const value = JSON.stringify({
name,
ts: now,
});
// Store the data in KV
// Storing the same value in metadata is a trick for optimized fetching
// but is only possible when the value is small.
await HELLO_NAME_KV.put(key, value, { metadata: value });
return new Response(`<h1>Goodbye, ${name}!</h1>`, {
headers: {
"content-type": "text/html",
},
});
}
// Route returns the names and timestamps of everyone that has been greeted
// Ex: https://hello-name-kv-demo.justin-cftemp.workers.dev/visitors
if (pathname.startsWith("/visitors")) {
// Fetch the entire list of visitors from KV
const visitorData = (await HELLO_NAME_KV.list()) || { keys: [] };
// Convert the visitor list into HTML
const visitors = visitorData.keys.reduce((list, visitor) => {
const info = JSON.parse(visitor.metadata);
return list + `<li>${info.name}, ${info.ts}</li>`;
}, "");
return new Response(`<h1>Visitors</h1><ul>${visitors}</ul> `, {
headers: {
"content-type": "text/html",
},
});
}
// 404 any other requests
return new Response("Not found", { status: 404 });
}
Please visit this link in your browser:
NOTE: Please use your name instead of the placeholder
https://hello-name-kv-demo.justin-cftemp.workers.dev/greeting/!!!YOUR_NAME_HERE!!!
The Cloudflare Worker should respond with a greeting to you.
Fetching Data from KV
Now, visit this link in your browser:
The Cloudflare Worker should respond with a list of all the visitors that have been received.
Notice that it may not instantly return the most recent visitors. Again, this is because KV is eventually consistent. In addition, queries from the KV have a 60 second default cache.
Accessing KV Data with Wrangler CLI
A developer can view the data stored in KV in the browser (😩) with the KV API or the Wrangler CLI.
wrangler kv:key list --namespace-id=240bcf8037a740e6a4320293b8d64329 | jq
"."
This data can be piped to a file for further review/backup.
... previous command + " > hello_kv_demo_data.json"
Deleting KV Data with Wrangler CLI
Deleting data can be done in the browser, one at a time via the CLI or in bulk with a special file of key/value pairs.
wrangler kv:key delete --namespace-id=240bcf8037a740e6a4320293b8d64329
"Neil_1636508237650"