How to bind to services
Hello,
I am new to workers and trying to understand service binding. In the wrangler init TypeScript project there is an environment interface:
What I am trying to understand is where the values
KVNamespace
or R2Bucket
are coming from. In my wranlger.toml I have a binding = "DB"
(in this case D1) but I don't know how to use env.DB
in the code since TypeScript says DB does not exist on type Env
. I understand it needs to be added into the interface but not sure how to reference it there.6 Replies
Those come from the
worker-types
packages found here (https://www.npmjs.com/package/@cloudflare/workers-types) for D1 you want something like
Oh, so those generic names are actually the names to use? I thought they were just examples and somehow I had to set these names somewhere. I didn’t realize they were types. I guess the comment made me think they were strings 🤦. Thank you!
Hmm, so I am using the
D1Database
type now but it seems to be undefined. Where I have the console log I am getting undefined. Any tips?
Can you share the error output
Here is the output
It doesn't look like the binding is being set correctly
@Cyb3r-Jok3 thanks, this lead me in the correct direction. For anyone else that gets this error, you have to make sure the name in the TypeScript interface matches your binding name. This example helped me figure that out.
https://developers.cloudflare.com/d1/get-started/#write-queries-within-your-worker
In my wrangler.toml my binding was DB but in the TypeScript interface I had DATABASE
Get started · Cloudflare D1 docs
This guide will instruct you through setting up and deploying your first database with D1. This guide assumes you already have a Cloudflare account.