Overview
R2 buckets provide:- S3-compatible object storage
- HTTP metadata and custom metadata
- Multipart uploads for large files
- Conditional operations (etag matching)
- Range requests for partial downloads
- Object lifecycle management
src/workerd/api/r2-bucket.h and r2-bucket.c++
Accessing R2 buckets
R2 buckets are bound to your worker in the environment:Uploading objects
Put object
Upload an object:Put with options
Set HTTP metadata and custom metadata:src/workerd/api/tests/r2-test.js:8
Put with checksums
Provide checksums for integrity verification:Downloading objects
Get object
Retrieve an object:src/workerd/api/tests/r2-test.js:88
Get object body types
R2 objects support multiple body reading methods:Get with options
Use conditional requests and range requests:src/workerd/api/r2-bucket.h:78
Object metadata
HTTP metadata
Access HTTP metadata:Custom metadata
Access custom metadata:Checksums
Verify object integrity:src/workerd/api/r2-bucket.h:122
Head object
Get object metadata without downloading the body:Deleting objects
Delete single object
Delete multiple objects
Listing objects
List objects in a bucket:List with options
Filter and paginate list results:Multipart uploads
Upload large files in parts:Resume multipart upload
Resume an existing upload:Abort multipart upload
Cancel an upload:Conditional operations
Conditional put
Only put if conditions are met:Conditional get
Only get if conditions are met:src/workerd/api/r2-bucket.h:91
Patterns
Serve files with proper headers
Upload with validation
Download with range support
Best practices
Set appropriate content types
Set appropriate content types
Always set content type for better client handling:
Use checksums for integrity
Use checksums for integrity
Verify uploads with checksums:
Use multipart for large files
Use multipart for large files
Upload large files (> 100 MB) in parts:
Use head for existence checks
Use head for existence checks
Check if objects exist without downloading:
Implementation details
R2 is implemented in:src/workerd/api/r2-bucket.h/.c++- Main R2 API (2000+ lines)src/workerd/api/r2-multipart.h/.c++- Multipart upload supportsrc/workerd/api/r2-admin.h/.c++- Admin operationssrc/workerd/api/r2-rpc.h/.c++- RPC client
src/workerd/api/r2-bucket.h:42:
Related APIs
- KV storage - Fast key-value storage
- Durable Objects - Coordinated state
- Fetch API - HTTP requests and responses
- Streams API - Streaming large uploads/downloads