Binding KV namespaces in Durable Objects

I’ve built my first Durable Objects project and it’s working extremely well, however I’m trying to do something straightforward and I just can’t understand where I’m going wrong.

I need to bind a KV namespace to my Durable Object. I’ve already added the kv_namespaces array to my wrangler.toml file. I understand from reading the documentation, that I can’t bind them like I do in other Workers (i.e. simply as global variables within the script). Instead, they need to bound in the Durable Object class definition (I think).

Please could someone provide a simple example of how I can bind a KV namespace to a Durable Object class definition and then use it to get a KV?

OK, this was easier than I thought. You simply need to set the binding to the env parameter in the class definition and can then use them elsewhere in your script, like in the fetch() method as per below:

export class Totals {
  constructor(state, env) {
    this.env = env
  }

async fetch(request) {
  const key = await this.env.INSERT_KV_NAMESPACE.get('key') // change key to KV key
  // insert other code here
}

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.