Cloudflare R2 for App Uploads: Practical Storage Guide for Developers in 2026

Cloudflare R2 for App Uploads: Practical Storage Guide for Developers in 2026

Cloudflare R2 is the object storage layer most developers reach for when their app needs to store user-uploaded files — profile photos, invoices, video clips, documents — without paying per-gigabyte egress fees. This guide walks through how R2 works in practice, when it beats S3 or Wasabi, and exactly how to wire it into an app deployed on CM Cloud App Hosting.


Why Object Storage Belongs Outside Your App Server

Every app that accepts file uploads eventually hits the same wall: the server’s local disk fills up, deploys wipe the upload folder, and scaling means files live on only one instance.

Object storage solves this permanently. Files sit in a remote bucket with a stable URL, your app server stays stateless, and storage scales to petabytes without you touching infrastructure.

CM Cloud App Hosting has no bundled local file persistence across deploys — which is exactly why pairing it with an external object store like R2 is the correct architecture from day one.


What Cloudflare R2 Actually Offers

R2 is Cloudflare’s S3-compatible object storage. The headline feature is zero egress fees — you pay to store bytes and to perform operations, but serving files to users costs nothing in bandwidth charges. That matters most when your app streams video, serves large documents, or operates in regions where bandwidth costs are high (including West Africa).

Key R2 specs in 2026:
– Storage: $0.015/GB per month
– Class A operations (PUT, POST): $4.50 per million
– Class B operations (GET): $0.36 per million
– Egress: $0.00 — always free
– Free tier: 10 GB storage, 1M Class A ops, 10M Class B ops per month
– S3-compatible API — any AWS SDK works without modification
– Custom domains via Cloudflare — serve files from uploads.yourdomain.com
– Public or private buckets — generate presigned URLs for private access


R2 vs S3 vs Wasabi: Which Storage Fits Your App?

Provider Storage (per GB/mo) Egress S3 Compatible Free Tier
Cloudflare R2 $0.015 $0.00 Yes 10 GB + 10M GET ops
AWS S3 $0.023 $0.09/GB Native 5 GB (12 months)
Wasabi $0.0068 $0.00* Yes None
Backblaze B2 $0.006 $0.01/GB** Yes 10 GB

*Wasabi charges egress if you exceed your storage volume in downloads per month.
**Backblaze B2 egress is free via Cloudflare CDN partnership.

When to pick R2: Your app serves files frequently to end users and you want predictable, egress-free billing. Ideal for profile photos, PDFs, and any user-facing media.

When S3 may win: You are deep in the AWS ecosystem and need Lambda triggers, S3 Event Notifications, or Intelligent Tiering. R2 does not support those.

When Wasabi wins: Pure archival with enormous storage volumes and low retrieval frequency.


Setting Up R2 for Your CM Cloud App: Step by Step

1. Create an R2 Bucket

Log into the Cloudflare dashboard → R2 Object Storage → Create bucket. Choose a region closest to your users (Cloudflare’s global network serves all regions with zero egress cost regardless).

Note your Account ID, then generate an R2 API token with Object Read & Write permissions.

2. Store Credentials as Environment Variables

Never hardcode credentials. In your CM Cloud App Hosting portal, navigate to your app → Environment Variables and add:

R2_ACCOUNT_ID=your_account_id
R2_ACCESS_KEY_ID=your_access_key
R2_SECRET_ACCESS_KEY=your_secret_key
R2_BUCKET_NAME=your_bucket_name
R2_PUBLIC_URL=https://your-custom-domain.com

CM Cloud injects these at runtime — they never appear in your git repository. The earlier CM Cloud article on deploying secrets safely covers the full variable management workflow.

3. Install the AWS SDK (S3-Compatible)

R2 speaks the S3 API, so you use the standard AWS SDK pointed at Cloudflare’s endpoint.

Node.js / Next.js:

npm install @aws-sdk/client-s3 @aws-sdk/s3-request-presigner

Python / FastAPI / Django:

pip install boto3

4. Configure the S3 Client to Point at R2

Node.js example:

import { S3Client } from "@aws-sdk/client-s3";

export const r2 = new S3Client({
  region: "auto",
  endpoint: `https://${process.env.R2_ACCOUNT_ID}.r2.cloudflarestorage.com`,
  credentials: {
    accessKeyId: process.env.R2_ACCESS_KEY_ID,
    secretAccessKey: process.env.R2_SECRET_ACCESS_KEY,
  },
});

Python example (boto3):

import boto3, os

r2 = boto3.client(
    "s3",
    endpoint_url=f"https://{os.environ['R2_ACCOUNT_ID']}.r2.cloudflarestorage.com",
    aws_access_key_id=os.environ["R2_ACCESS_KEY_ID"],
    aws_secret_access_key=os.environ["R2_SECRET_ACCESS_KEY"],
    region_name="auto",
)

5. Upload Files from Your App Handler

A Node.js / Express upload handler using multer in memory:

import { PutObjectCommand } from "@aws-sdk/client-s3";
import { r2 } from "./r2Client.js";
import multer from "multer";
import { v4 as uuid } from "uuid";

const upload = multer({ storage: multer.memoryStorage() });

app.post("/upload", upload.single("file"), async (req, res) => {
  const key = `uploads/${uuid()}-${req.file.originalname}`;
  await r2.send(new PutObjectCommand({
    Bucket: process.env.R2_BUCKET_NAME,
    Key: key,
    Body: req.file.buffer,
    ContentType: req.file.mimetype,
  }));
  const url = `${process.env.R2_PUBLIC_URL}/${key}`;
  res.json({ url });
});

Store url in your database. The file lives in R2; your app server stays stateless and redeployable.

6. Generate Presigned URLs for Private Files

For private documents (contracts, medical records, invoices), keep the bucket private and generate a presigned URL that expires:

import { GetObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";

const url = await getSignedUrl(r2, new GetObjectCommand({
  Bucket: process.env.R2_BUCKET_NAME,
  Key: fileKey,
}), { expiresIn: 3600 }); // 1 hour

Send the signed URL to the authenticated user. After one hour it expires automatically.


File Type Validation: Do This on the Server

Never trust the client’s reported MIME type. On your CM Cloud App Hosting backend, validate using a library that reads the actual file bytes:

  • Node.js: file-type package — reads magic bytes
  • Python: python-magic — libmagic bindings

Reject anything that doesn’t match your allowlist before it reaches R2. Your app is the backend — apply all security logic server-side.


Connecting a Custom Domain to R2

In Cloudflare R2 → your bucket → Settings → Custom Domain, add uploads.yourdomain.com. Cloudflare provisions the DNS record and serves your files through its global CDN automatically — still with zero egress fees.

Set R2_PUBLIC_URL=https://uploads.yourdomain.com in your CM Cloud environment variables and your file URLs look professional and are CDN-accelerated.


What CM Cloud App Hosting Provides

CM Cloud App Hosting runs your server-side code (Node.js, Python, Laravel, PocketBase) in a fully managed runtime. CM Cloud handles nginx, systemd, and process supervision — you push code and the platform runs it.

A CI/CD deploy hook is included: generate a secret URL in the portal, call it from a GitHub Actions step, and every git push redeploys your app automatically. Pair that with R2 for uploads and an external managed database and you have a production-grade, stateless application architecture.

View App Hosting pricing at cmcloudhosting.com/pricing


CM Cloud App Hosting vs Competitors for R2-Powered Apps

Provider Starter Price XAF EUR R2-Ready Runtime Managed Runtime Layer
CM Cloud App Hosting $7.99/mo XAF 5,000 €7.40 Yes — env vars, S3 SDK works out of box Yes — nginx + systemd managed
Railway $5/mo (usage-based Hobby) ~XAF 3,100 ~€4.60 Yes Partial — buildpacks
Render $7/mo (individual) ~XAF 4,350 ~€6.50 Yes Yes
Hostinger (VPS promo*) $0–$6.79/mo promotional varies varies Self-managed only No — you configure everything
DigitalOcean Droplet $6/mo ~XAF 3,700 ~€5.55 Yes — self-configured No — you manage the stack

*Hostinger promotional pricing is introductory; renewal rates unconfirmed. For a direct comparison, see CM Cloud vs Hostinger 2026.

CM Cloud’s managed runtime means you don’t configure nginx or systemd — you write upload handlers and push code.


AI Credits for Storage-Related Tooling

CM Cloud includes AI credits on every plan, usable for AI-assisted features in the portal. Top up from $1.00 / XAF 500 / €0.93 for 25 credits — no subscription required.

Pack USD XAF EUR Credits
Entry $1.00 XAF 500 €0.93 25
Standard $4.00 XAF 2,000 €3.72 100
Pro $10.00 XAF 5,000 €9.30 250

Architecture Summary: Stateless App + R2 Uploads

  • CM Cloud App Hosting → runs your Node.js, Python, Laravel, or PocketBase backend
  • Cloudflare R2 → stores all user-uploaded files, served via CDN with zero egress cost
  • External managed database → stores file URLs and metadata
  • GitHub Actions + CM Cloud deploy hook → automatic deploys on every push

This stack is fully stateless, horizontally scalable, and costs less than $10/month for a production app at early scale.


Start Deploying

Your app backend runs on CM Cloud App Hosting at $7.99/mo (XAF 5,000 / €7.40). R2 has a generous free tier that covers most early-stage apps. Wire them together with environment variables and the S3 SDK and you have a production-grade upload pipeline in an afternoon.

See full pricing and deploy your app → cmcloudhosting.com/pricing

Scroll to Top