Skip to content

Instantly share code, notes, and snippets.

Created December 5, 2021 16:48
  • Star 20 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Tips on how to use a KV namespace with Cloudflare Pages
This gist aims to show you how to use KV datastore using Cloudflare pages. The reason I created this quick guide is it took
me almost 2 weeks to get it working, mainly because it is very new and the documentation is not up fully fleshed out yet
Install wrangler 2
In your project create a folder called functions this is where the workers' files go
create a KV namespace in your Cloudflare dashboard
add a binding in your Cloudflare pages project which can be found in settings/functions. I called this variable ALLOW_TEST and selected then namespace but you can call it whatever you want
Create a file in your functions directory and put in the following code.
export async function onRequest(context) {
try {
// Contents of context object
const {
request, // same as existing Worker API
env, // same as existing Worker API
params, // if filename includes [id] or [[path]]
waitUntil, // same as ctx.waitUntil in existing Worker API
next, // used for middleware or to fetch assets
data, // arbitrary space for passing data between middlewares
} = context;
//get the ENV var for the binding
//note this is the variable name you added in the KV bindings in your Cloudflare pages set up.
const KV = context.env.ALLOW_TEST;
//put a variable in place.
KV.put("foo", "bar",{})
//The following are commented out and are here an example on how to use it.
//get a key
//const key = await KV.get("foo")
//delete a key
//list the keys
const value = await KV.list()
return new Response('boo');
} catch (err) {
//flatten the error
let json = JSON.stringify(err)
//return the error
return new Response(err);
from the root of your project run the following command, again ALLOW_TEST is the variable name you added in the KV bindings in your Cloudflare pages set up.
wrangler pages dev functions --kv=ALLOW_TEST
These are things I noted whilst figuring this out.
You have to use a try-catch when you deploy it to the Cloudflare but locally using wrangler it works fine
when you are running locally it will not store the data in the Cloudflare dashboard, which makes sense as it is likely to be dev data
There is no logging for Cloudflare pages (that I can find) and if something goes wrong you get their standard error page so that is why I flatten the error message and return it
You can see this file deployed here
and the source code is here
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment