Storage
Learn how to set up and use Cloudflare R2 for file uploads and media processing
TanStarter uses Cloudflare R2 for file storage, accessing R2 buckets directly via Wrangler bindings without needing S3-compatible API keys.
Setup
Configure Cloudflare API Token
Please complete the Cloudflare API Token configuration first, ensuring the Token includes the Account > Workers R2 Storage > Edit permission.
Create R2 Bucket
You can create an R2 bucket via the Cloudflare Dashboard or Wrangler CLI:
- Create a new R2 bucket:
pnpm wrangler r2 bucket create your-bucket-name- Log in to the Cloudflare Dashboard
- Go to Storage & Databases > R2 Object Storage
- Click Create Bucket
- Enter a globally unique bucket name
- Select a region close to your target audience
- Click Create Bucket
Configure Wrangler Binding
Configure the R2 bucket binding in wrangler.jsonc:
{
"r2_buckets": [
{
"binding": "BUCKET",
"bucket_name": "your-bucket-name" // Change to your bucket name
}
]
}Update Website Configuration
In most cases, the default configuration works fine. If you need to change it, modify the storage config in src/config/website.ts:
export const websiteConfig = {
// ...other config
storage: {
enable: true,
provider: 'r2',
maxFileSize: 10 * 1024 * 1024, // 10MB
allowedTypes: [], // empty array = allow all types
userFilesFolder: 'userfiles',
},
// ...other config
}If you are setting up your environment, you can go back to the Environment Configuration doc and continue. The rest of this document can be read later.
Environment Configuration
Set up environment variables
Core Features
- File upload and download
- Organize files using folders
- Auto-generated file paths and naming
- File info queries and user file listing
- Configurable file size and type limits
Usage
Basic File Operations
TanStarter provides simple APIs for common file operations:
import { uploadFile, deleteFile, downloadFile, getFileInfo } from '@/storage';
// Upload a file
const { url, key } = await uploadFile(
fileBuffer,
'original-filename.jpg',
'image/jpeg',
{ folder: 'uploads/images' }
);
// Delete a file
await deleteFile(key);
// Download a file
const stream = await downloadFile(key);
// Get file info
const info = await getFileInfo(key);User File Management
import { listUserFiles, uploadFile } from '@/storage';
// Upload a user file
const { url, key, metadata } = await uploadFile(
file,
filename,
contentType,
{ folder: 'userfiles', userId: 'user_123' }
);
// List all files for a user
const { objects, hasMore, nextCursor } = await listUserFiles('user_123');Best Practices
- File Organization: Use folders to organize files by type or purpose
- File Size Limits: Set reasonable file size limits to prevent abuse
- File Type Validation: Validate file types on both client and server side for security
Next Steps
Now that you understand how to use file storage in TanStarter, explore these related topics:
TanStarter Docs