Skip to content

Architecture Overview

Temp edited this page Feb 23, 2026 · 10 revisions

Architecture Overview

Technical architecture and design of R2-Manager-Worker.

System Architecture

┌─────────────────────────────────────────────────────────────┐
│                     User's Browser                          │
│                    (React 19 App)                           │
│  • Vite dev server (local) or CDN (production)              │
│  • React components and state management                    │
│  • TypeScript for type safety                               │
└──────────────────────┬──────────────────────────────────────┘
                       │
                       │ HTTPS
                       ▼
┌─────────────────────────────────────────────────────────────┐
│              Cloudflare Access (Zero Trust)                 │
│  • JWT token validation                                     │
│  • GitHub OAuth integration                                 │
│  • Access policies enforcement                              │
└──────────────────────┬──────────────────────────────────────┘
                       │
                       │ Authenticated Request
                       ▼
┌─────────────────────────────────────────────────────────────┐
│           Cloudflare Workers (Edge Runtime)                 │
│                  (TypeScript)                               │
│  • Request routing and handling                             │
│  • JWT payload extraction                                   │
│  • API business logic                                       │
│  • Signed URL generation and validation                     │
└──────────────────────┬──────────────────────────────────────┘
        ┌──────────────┼──────────────┐
        │              │
        ▼              ▼
   ┌─────────┐   ┌──────────┐
   │   R2    │   │  Assets  │
   │ Buckets │   │  (Vite)  │
   │(S3 API) │   │          │
   └─────────┘   └──────────┘

Component Stack

Frontend

Layer Technology Purpose
UI Framework React Component-based UI
Build Tool Vite Fast development and bundling
Language TypeScript Type-safe JavaScript
Styling Vanilla CSS No dependencies, simple styling
Crypto spark-md5 MD5 checksum calculation for upload verification

Backend

Layer Technology Purpose
Runtime Cloudflare Workers Serverless edge computing
Language TypeScript Type-safe Worker code
Storage R2 Object storage (S3-compatible)
Auth Cloudflare Access Zero Trust authentication

Deployment

Component Tool Purpose
Frontend Build Vite Optimized production build
Deployment Wrangler Cloudflare Workers CLI
Config wrangler.toml Worker and resource configuration

File Organization

R2-Manager-Worker/
│
├── src/                           # Frontend source code
│   ├── app.tsx                   # Main App component
│   ├── filegrid.tsx              # File browser UI component
│   ├── main.tsx                  # React entry point
│   ├── app.css                   # Global styles
│   ├── vite-env.d.ts             # Vite environment types
│   │
│   └── services/                 # Service layer
│       ├── api.ts                # HTTP client and API calls
│       └── auth.ts               # Authentication utilities
│
├── worker/                        # Backend Worker code
│   ├── index.ts                  # Worker main file
│   │                             # • Request handler
│   │                             # • Route matching
│   │                             # • API endpoints
│   │                             # • JWT validation
│   ├── routes/                   # API route handlers
│   │   └── local-uploads.ts     # Local uploads GET/PUT endpoints
│   └── utils/                    # Helper utilities
│
├── public/                        # Static assets
│   ├── favicon.ico
│   ├── logo.png
│   ├── manifest files
│   └── other images
│
├── dist/                          # Production build output
│   ├── index.html
│   ├── assets/                   # Bundled JS and CSS
│   └── static files
│
├── .env.example                   # Environment variables template
├── .env                           # Local environment (ignored)
├── wrangler.toml.example          # Wrangler config template
├── wrangler.toml                  # Actual config (ignored)
├── package.json                   # Dependencies
├── tsconfig.json                  # TypeScript config
├── tsconfig.app.json              # App-specific TS config
├── tsconfig.node.json             # Node-specific TS config
├── vite.config.ts                 # Vite build configuration
└── eslint.config.js               # Linting rules

Data Flow

File Upload Flow

1. User selects file in browser
   └─> File stored in memory

2. File size checked against limit
   └─> Determine if chunking needed

3. If large (>10MB):
   └─> Split into 10MB chunks

4. For each chunk:
   a. Add headers (chunk index, total chunks)
   b. POST to /api/files/:bucket/upload
   c. Worker receives request
   d. PUT to Cloudflare R2 API
   e. R2 stores object
   f. Return success

5. On final chunk:
   └─> Trigger cache refresh

File Download Flow

1. User selects file and clicks Download
   └─> Call /api/files/:bucket/signed-url/:file

2. Worker generates signed URL:
   a. Create download path
   b. Add timestamp
   c. Calculate HMAC signature
   d. Return full URL

3. User's browser makes GET request to signed URL
   └─> Request reaches Worker

4. Worker validates signature:
   a. Extract path and signature from URL
   b. Recalculate expected signature
   c. Compare signatures
   d. If match: continue

5. Worker fetches file from R2:
   a. Call R2 API with authentication
   b. Stream file to browser
   c. Add Content-Disposition header
   d. Browser starts download

6. Browser receives file
   └─> User's Downloads folder

Authentication Flow

1. User visits application
   └─> Request reaches Cloudflare Access

2. Cloudflare Access checks JWT cookie
   └─> If missing, redirect to login

3. User redirected to GitHub OAuth
   └─> User logs in with GitHub

4. GitHub redirects back with auth code
   └─> Cloudflare Access exchanges for JWT

5. JWT set as cookie cf-access-jwt-assertion
   └─> User redirected to app

6. Browser sends requests with JWT cookie
   └─> Worker extracts JWT from header

7. Worker validates JWT:
   a. Get JWT from request
   b. Fetch Cloudflare's public keys
   c. Verify signature
   d. Check issuer and audience
   e. Extract user email

8. User email available in Worker
   └─> Can be used for authorization

API Request Lifecycle

1. Browser Request
   └─> HTTPS to Cloudflare edge

2. Cloudflare Access
   └─> Validate JWT and policies

3. Worker Receives Request
   a. Parse URL and method
   b. Log request details
   c. Extract parameters

4. Route Matching
   a. Check if /api/buckets
   b. Check if /api/files
   c. Check if signed download
   d. else 404

5. Authentication Check
   a. Validate JWT (skip for downloads)
   b. Extract user email
   c. If invalid, return 401

6. Business Logic
   a. Call Cloudflare R2 API
   b. Process data
   c. Format response

7. Return Response
   a. Set CORS headers
   b. Set content type
   c. Serialize response
   d. Send to browser

8. Browser Receives
   └─> JavaScript processes response
       └─> Update UI

Key Design Decisions

Why TypeScript?

  • ✅ Type safety prevents runtime errors
  • ✅ Better IDE autocomplete and documentation
  • ✅ Self-documenting code
  • ✅ Easier refactoring
  • ✅ Catches bugs at compile time

Why React?

  • ✅ Component-based architecture
  • ✅ Efficient updates with virtual DOM
  • ✅ Large ecosystem and community
  • ✅ Excellent developer tools
  • ✅ React 19 has latest features

Why Vite?

  • ✅ Ultra-fast dev server (instant HMR)
  • ✅ Smaller bundle sizes
  • ✅ Fast production builds
  • ✅ Native ES modules support
  • ✅ Plugin ecosystem

Why Cloudflare Workers?

  • ✅ Global edge deployment
  • ✅ No servers to manage
  • ✅ Excellent performance
  • ✅ Generous free tier
  • ✅ Deep integration with R2

Why R2?

  • ✅ S3-compatible API
  • ✅ Zero egress fees (huge cost saving)
  • ✅ Global edge caching
  • ✅ Integrates with Workers
  • ✅ Excellent performance

Performance Optimizations

Frontend

  • Code Splitting - Vite automatically splits chunks
  • Lazy Loading - Components load on demand
  • Asset Compression - Gzip/brotli compression
  • Caching - Browser caching of assets
  • CDN Delivery - Cloudflare edge network

Backend

  • Streaming Responses - Large files streamed efficiently
  • Batch Operations - Group API calls to reduce latency
  • Rate Limiting - Delays prevent API throttling
  • Pagination - Large result sets paginated
  • Caching - HTTP caching headers utilized

API Efficiency

  • Direct R2 Access - No intermediate database layer
  • Efficient Queries - Optimized R2 API calls
  • Connection Pooling - Worker connections reused
  • Request Optimization - Minimal API calls

Security Architecture

Authentication

  • Zero Trust - All requests must be authenticated
  • JWT Validation - Tokens verified on every request
  • Public Keys - Downloaded from Cloudflare's JWKS endpoint
  • Signature Verification - Tokens can't be forged

Authorization

  • Access Policies - Enforced by Cloudflare Access
  • GitHub Integration - Use GitHub identities
  • Granular Policies - Path-based and action-based rules

Data Protection

  • HTTPS Only - All traffic encrypted
  • Signed URLs - Downloads validated with HMAC
  • No Credential Storage - No passwords stored
  • Audit Ready - Logging infrastructure ready

Scalability

Horizontal Scaling

  • Edge Network - Cloudflare has 300+ data centers
  • Auto-scaling - Workers scale automatically
  • Global Deployment - Automatic in all regions
  • No Capacity Planning - Scale with demand

Vertical Scaling

  • R2 Growth - Unlimited storage
  • Request Capacity - Auto-scales with load
  • No Limits - Growth limited by plan, not architecture

Development Workflow

Local Development

Terminal 1: npm run dev          # Vite dev server
Terminal 2: npx wrangler dev     # Local Worker
Browser:   http://localhost:5173 # Frontend

Hot Module Replacement

  • Frontend - React Fast Refresh (instant updates)
  • Worker - Wrangler auto-reload (instant updates)
  • No manual restart - Changes appear immediately

Production Deployment

npm run build       # Build frontend
npx wrangler deploy # Deploy to Cloudflare

Next Steps:

R2 Bucket Manager Wiki

Getting Started

Core Features

Development

Security & Authentication

Support & Resources

External Links

Clone this wiki locally