Object Storage & R2

36. Object Storage: S3 Client, Cloudflare R2 & Presigned Uploads

Architect scalable media and file storage with AWS SDK v3, presigned client upload tokens, and zero-egress Cloudflare R2 buckets.

storage-s3-r2.ts
import { S3Client, PutObjectCommand, GetObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';

// 1. Initialise Cloudflare R2 / AWS S3 Client
export const s3 = new S3Client({
  region: 'auto',
  endpoint: `https://${process.env.CLOUDFLARE_ACCOUNT_ID}.r2.cloudflarestorage.com`,
  credentials: {
    accessKeyId: process.env.R2_ACCESS_KEY_ID!,
    secretAccessKey: process.env.R2_SECRET_ACCESS_KEY!
  }
});

// 2. Generate short-lived Presigned Upload URL (Zero backend bandwidth consumed)
export async function createPresignedUploadUrl(bucket: string, key: string, contentType: string) {
  const command = new PutObjectCommand({
    Bucket: bucket,
    Key: key,
    ContentType: contentType
  });

  // Client uploads directly to R2 / S3 via HTTP PUT
  return await getSignedUrl(s3, command, { expiresIn: 3600 });
}

Object Storage: S3 Client, Cloudflare R2 & Presigned Uploads

Modern file architectures decouple binary storage from application compute. Instead of routing gigabytes of user file uploads through web servers, clients stream data directly to object storage buckets using short-lived presigned URLs.

  • AWS SDK v3 (@aws-sdk/client-s3): Tree-shakable, modular client architecture tailored for edge runtimes and serverless functions.
  • Presigned Upload URLs: The application server cryptographically signs a PUT command; the browser uploads directly to S3/R2 with zero server CPU or bandwidth overhead.
  • Cloudflare R2 (Zero Egress): 100% S3-compatible API with zero data transfer egress fees, drastically cutting bandwidth expenses for media-heavy web applications.
  • Multipart Streaming: Efficient chunking for multi-gigabyte video or archive files with parallel chunk verification and resumption.
Presigned S3 / R2 Upload Generator AWS SDK v3
Storage & Egress Cost Comparison Cost Optimisation
AWS S3 Standard

£191.50

Includes £0.09/GB egress
Cloudflare R2

£7.50

£0 Egress Fees
Monthly Savings

+£184.00

96% cost reduction