Uploading Files to Cloudflare R2 from the Frontend (No Axios Needed!)
Nurul Islam Rimon

Nurul Islam Rimon @nurulislamrimon

About: Thanks for being here! I'm Nurul Islam Rimon, a MERN & PERN stack developer. I'm a student of competitive programming. I love to explore new technology.

Location:
Chaprashirhat, Kabirhat, Noakhali
Joined:
Jan 20, 2024

Uploading Files to Cloudflare R2 from the Frontend (No Axios Needed!)

Publish Date: May 13
0 0

Are you building a file upload feature for your web app?
Want to keep things fast and efficient without using any backend for the actual upload?
Let me show you how to upload files directly to Cloudflare R2 using a pre-signed URL and plain fetch — no axios, no SDKs, no stress.

Step 1: Generate a Signed Upload URL on the Server
To avoid exposing your R2 credentials on the frontend, you should generate a signed PUT URL on the backend.
Click here to read article about generating signed url.

Here’s an example response from your backend API:

{
  "signedUrl": "https://your-bucket.r2.cloudflarestorage.com/filename.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&..."
}
Enter fullscreen mode Exit fullscreen mode

Step 2: Upload from the Frontend Using Fetch
Here’s a minimal example using an HTML file input and plain JavaScript:

✅ HTML:

<input type="file" id="fileInput" />
<button onclick="uploadFile()">Upload</button>
Enter fullscreen mode Exit fullscreen mode

✅ JavaScript:

async function uploadFile() {
  const input = document.getElementById('fileInput');
  const file = input.files[0];
  if (!file) return alert("Please select a file!");

  // 1. Get a signed upload URL from your backend
  const res = await fetch(`/api/r2-signed-url?filename=${encodeURIComponent(file.name)}`);
  const { signedUrl } = await res.json();

  // 2. Upload the file directly to R2
  const uploadRes = await fetch(signedUrl, {
    method: 'PUT',
    body: file,
  });

  if (uploadRes.ok) {
    alert("✅ Upload successful!");
  } else {
    alert("❌ Upload failed.");
  }
}
Enter fullscreen mode Exit fullscreen mode

Why This Works

  • No extra libraries (no axios)
  • Faster uploads because the file goes straight from browser → Cloudflare
  • Secure: your app’s R2 credentials stay on the server
  • Scalable: you don’t stress your backend with file payloads

Don't Forget CORS!
Make sure your R2 bucket has CORS enabled for PUT requests.
Example:

<CORSRule>
  <AllowedMethod>PUT</AllowedMethod>
  <AllowedOrigin>*</AllowedOrigin> <!-- or restrict to your domain -->
  <AllowedHeader>*</AllowedHeader>
</CORSRule>
Enter fullscreen mode Exit fullscreen mode

📌 Author: Nurul Islam Rimon
🔧 Fullstack Developer | Expertsquad

Comments 0 total

    Add comment