Setting up bindings for KV and Qwik

I've got wrangler to log a KVNamespace, but the result of await platform["KV"].get(key) is always null. Can anyone provide examples of wrangler.toml and a slightly more detailed description of setting up a Qwik project to use KV locally?
5 Replies
jculveyhouse
jculveyhouse7mo ago
Can you give await platform.env["MY_KV_NAMESPACE"] a shot? If you're starting from scratch, you can run npm create cloudflare@latest -- --framework qwik. Out of the box it will provide a wrangler.toml including bindings examples. Uncomment the KV example and run build-cf-types to regenerate a type definition for the platform object and it will include your KV
// src/routes/kv-demo/index.ts
import type { RequestHandler } from "@builder.io/qwik-city";

export const onGet: RequestHandler = async ({ platform, json }) => {
const counter = parseInt(
(await platform.env.MY_KV_NAMESPACE.get("count")) || "0"
);
await platform.env.MY_KV_NAMESPACE.put("count", String(counter + 1));

json(200, { counter, success: true });
};
// src/routes/kv-demo/index.ts
import type { RequestHandler } from "@builder.io/qwik-city";

export const onGet: RequestHandler = async ({ platform, json }) => {
const counter = parseInt(
(await platform.env.MY_KV_NAMESPACE.get("count")) || "0"
);
await platform.env.MY_KV_NAMESPACE.put("count", String(counter + 1));

json(200, { counter, success: true });
};
Brandon Pittman
Brandon PittmanOP7mo ago
@jculveyhouse Thanks for the response! Your example worked in my existing app. I checked my dashboard in Cloudflare after and couldn't find the count value in my KV namespace though. I'm not sure where the data is actually being saved. 🤔
Brandon Pittman
Brandon PittmanOP7mo ago
My dashboard shows these two I manually added on the CF site:
No description
Brandon Pittman
Brandon PittmanOP7mo ago
While the onGet you shared shows this in the browser:
{"counter":10,"success":true,"foo":null}
{"counter":10,"success":true,"foo":null}
The namespace ID on the CF dashboard matches the ID that npx wrangler kv:namespace list outputs too. When I run the wrangler dev command and interact with the KV, I'm not interacting with the same KV on the web, am I? 🤦‍♂️ @jculveyhouse It totally works. My mental model was wrong. I was expecting to see data from the CF dashboard locally.
jculveyhouse
jculveyhouse7mo ago
Awesome, glad it worked. If you run into any more issue let us know 😄
Want results from more Discord servers?
Add your server