How to Generate Presigned URLs for R2 When Using Cloudflare Workers (And Make Sure They Actually Work)
So you want to let users upload files directly to Cloudflare R2 from their browser? Great idea! Presigned URLs are the way to do it. You follow the documentation, you generate a presigned URL, and… 403 Forbidden. Let me show you how to fix all of this. Step 1: Use the Right Library Don’t use the official AWS SDK. It doesn’t work in Cloudflare Workers because it needs Node.js APIs that Workers don’t have. Do use aws4fetch - it’s built specifically for Workers and uses the Web APIs that Workers actually support. 1 npm install aws4fetch Step 2: Generate the Presigned URL Here’s the code that actually works: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 import { AwsClient } from 'aws4fetch'; async function generatePresignedUrl( key: string, // e.g., "uploads/myfile.mp3" expiresIn: number // seconds, e.g., 3600 = 1 hour ) { // Create the client const client = new AwsClient({ accessKeyId: env.R2_ACCESS_KEY_ID, secretAccessKey: env.R2_SECRET_ACCESS_KEY,…
No comments yet. Log in to reply on the Fediverse. Comments will appear here.