Accessing KV Key from a worker

#1

I have a question about accessing the data stored in a KV namespace from my worker. I have used the CloudFlare API to create a key-value pair in the namespace STAGING using a HTTP PUT to
https://api.cloudflare.com/client/v4/accounts/***/storage/kv/namespaces/***/values/SLACK_TOKEN

How do i access that same key from my worker? I have read this article, which included the following snippet

const tokenInfo = await TOKEN_STORE.get(token, "json")
 if (!tokenInfo) {
}

but couldn’t see where TOKEN_STORE was declared.

cheers

#2

You have to create a binding to the namespace in the Cloudflare Workers Editor. Go to the Resources Tab in there and there you can make the bindings. Then you have to “Deploy” inside the Editor as well, or the binding will not be applied.

EDIT: Bindings can also be done via API now, se here: https://developers.cloudflare.com/workers/api/resource-bindings/kv-namespaces/

#3

I am using the serverless framework to deploy the worker. Is there an example of how to create the binding in serverless

#4

You cannot create bindings via the API yet, you have to login to your Cloudflare panel, go to your Workers tab and press the Launch editor button. Then follow the steps i laid out above.

#5

The script that you see in the Editor is the same script that you have deployed with the serverless framework - so after you add the KV bindings and hit “Deploy”, it would be the same as saving the bindings (since you’re re-deploying the script that already exist).

#6

In general - It’s key that you know about the Editor, since this is the only place where you can debug a worker script.

#7

After further investigation, it seems that the serverless Cloudflare Worker plugin does support the KV binding

#8

Great to know :+1: