Beginner: Cannot connect to R2 via Worker

Hi everyone, I followed the tutorial https://developers.cloudflare.com/r2/api/workers/workers-api-usage/ and created a worker. While testing it, I am getting an error: message: "Cannot read properties of undefined (reading 'put')", exception: { stack: " at Object.fetch (index.js:971:30)", name: "TypeError", message: "Cannot read properties of undefined (reading 'put')", timestamp: 1733778270490, }, If I remove the R2 related code, it works properly. I have tried both locally and after deployment. From CLI, I created the bucket as shown in the tutorial. I can see both the bucket and worker from the dashboard.
Cloudflare Docs
Use R2 from Workers · Cloudflare R2 docs
C3 (create-cloudflare-cli) is a command-line tool designed to help you set up and deploy Workers & Pages applications to Cloudflare as fast as possible.
4 Replies
Walshy
Walshy3mo ago
share your code + wrangler.toml
psych
psychOP3mo ago
@Walshy Thank you for responding! index.js /** * Welcome to Cloudflare Workers! This is your first worker. * * - Run npm run dev in your terminal to start a development server * - Open a browser tab at http://localhost:8787/ to see your worker in action * - Run npm run deploy to publish your worker * * Learn more at https://developers.cloudflare.com/workers/ */ export default { async fetch(request, env, ctx) { // return new Response('Hello World!'); const url = new URL(request.url); const key = url.pathname.slice(1); switch (request.method) { case "PUT": await env.MY_BUCKET.put(key, request.body); return new Response(Put ${key} successfully!); default: return new Response(${request.method} is not allowed., { status: 405, headers: { Allow: "PUT", }, }); } }, }; wrangler.toml (only change is the name of the bucket) # Bind an R2 Bucket. Use R2 to store arbitrarily large blobs of data, such as files. # Docs: https://developers.cloudflare.com/workers/wrangler/configuration/#r2-buckets # [[r2_buckets]] # binding = "MY_BUCKET" # bucket_name = "faltu-bucket"
harshil1712
harshil17123mo ago
Your bindings look wrong. You need to remove the #. Your R2 bindings should look like:
[[r2_buckets]]
binding = "MY_BUCKET"
bucket_name = "faltu-bucket"
[[r2_buckets]]
binding = "MY_BUCKET"
bucket_name = "faltu-bucket"
psych
psychOP3mo ago
Omg that's such a silly mistake. Sorry. And thank you for looking into it!

Did you find this page helpful?