KV Storage is a cache that Cloudflare makes available within our Workers. It replicates across multiple CDN nodes, making it a super performant way to cache data.
In this lesson, we create a new KV store using the Wrangler CLI, and bind it to our Cloudflare worker using the wrangler.toml
configuration file.
Additionally, we create a preview
store to use in development mode.
Create a KV Store
npx wrangler kv:namespace create "ARTICLES"
Create a preview KV Store
npx wrangler kv:namespace create "ARTICLES" --preview
Bind KV to Cloudflare Worker
kv_namespaces = [
{ binding = "replace-with-your-kv-name", id = "replace-with-your-kv-production-id", preview_id = "replace-with-your-kv-preview-id" }
]
Run wrangler development server
npx wrangler dev
Instructor: [0:00] Every time a user navigates to one of our routes, we're making a request to the Supabase origin server, but each of these Cloudflare workers is running at a CDN node as close as possible to the user making that request. [0:11] To reduce the number of trips to that origin server, we need to cache this value that we get back from Supabase as close to our users as possible.
[0:18] Type npx wrangler kv:Namespace create to create a new KV store, where we can cache these values. We need to give it a name, mine's going to be articles. Once that's finished, we'll see this binding=articles and then an ID for our KV store.
[0:35] Let's copy this whole object here and open up our wrangler.toml file. We then need to create a new key for kv_namespaces, and set this equal to an array and paste that object for our new KV store.
[0:50] Now, if we run npx wrangler dev to start our development server, we get this error because we shouldn't use the same KV store in development mode as we are in production.
[1:00] We can create a KV store specifically for running in development mode by running the same command npx wrangler kv:namespace create articles and appending --preview. You'll see this has given us another configuration object.
[1:13] We actually only need the preview ID for this one, so we can copy that and then paste that into our wrangler.toml file. Now, if we run our npx wrangler dev command again, see, our development server is back up and running, but we've also attached to this KV namespace for articles.