|
| 1 | +# File Storage Setup |
| 2 | + |
| 3 | +> **Note**: This documentation was written by Claude 3.5 Sonnet. |
| 4 | +
|
| 5 | +This project supports **cloud-based file storage** for handling file uploads and downloads. |
| 6 | + |
| 7 | +## Overview |
| 8 | + |
| 9 | +Files are stored with **public access** by default, making them accessible via URL. This is useful for sharing uploaded content, displaying images, and integrating with external services. |
| 10 | + |
| 11 | +## Storage Drivers |
| 12 | + |
| 13 | +The project supports two storage backends: |
| 14 | + |
| 15 | +- **Vercel Blob** - Default for all deployments (recommended) |
| 16 | +- **S3** - Planned for AWS/S3-compatible storage |
| 17 | + |
| 18 | +**Vercel Blob** is the default storage driver and works seamlessly in both local development and production environments. |
| 19 | + |
| 20 | +## Configuration |
| 21 | + |
| 22 | +### Environment Variables |
| 23 | + |
| 24 | +```ini |
| 25 | +# Storage driver selection (defaults to vercel-blob) |
| 26 | +FILE_STORAGE_TYPE=vercel-blob # or s3 (coming soon) |
| 27 | + |
| 28 | +# Optional: Subdirectory prefix for organizing files |
| 29 | +FILE_STORAGE_PREFIX=uploads |
| 30 | + |
| 31 | +# === Vercel Blob (FILE_STORAGE_TYPE=vercel-blob) === |
| 32 | +BLOB_READ_WRITE_TOKEN=<auto on Vercel> |
| 33 | +VERCEL_BLOB_CALLBACK_URL= # Optional: For local webhook testing with ngrok |
| 34 | + |
| 35 | +# === S3 (FILE_STORAGE_TYPE=s3, not yet implemented) === |
| 36 | +# FILE_STORAGE_S3_BUCKET= |
| 37 | +# FILE_STORAGE_S3_REGION= |
| 38 | +# AWS_ACCESS_KEY_ID= |
| 39 | +# AWS_SECRET_ACCESS_KEY= |
| 40 | +``` |
| 41 | + |
| 42 | +### Quick Start with Vercel Blob |
| 43 | + |
| 44 | +Vercel Blob works in both local development and production environments: |
| 45 | + |
| 46 | +1. Go to your Vercel project → **Storage** tab |
| 47 | +2. Click **Connect Database** → **Blob** → **Continue** |
| 48 | +3. Name it (e.g., "Files") and click **Create** |
| 49 | +4. Pull environment variables locally: |
| 50 | + |
| 51 | +```bash |
| 52 | +vercel env pull |
| 53 | +``` |
| 54 | + |
| 55 | +That's it! File uploads will now work seamlessly in both development and production. |
| 56 | + |
| 57 | +## Client Upload |
| 58 | + |
| 59 | +The `useFileUpload` hook **automatically selects the optimal upload method** based on your storage backend: |
| 60 | + |
| 61 | +- **Vercel Blob**: Direct browser → CDN upload (fastest, default) |
| 62 | +- **S3**: Presigned URL upload (when implemented) |
| 63 | + |
| 64 | +```tsx |
| 65 | +"use client"; |
| 66 | + |
| 67 | +import { useFileUpload } from "hooks/use-presigned-upload"; |
| 68 | + |
| 69 | +function FileUploadComponent() { |
| 70 | + const { upload, isUploading } = useFileUpload(); |
| 71 | + |
| 72 | + const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => { |
| 73 | + const file = e.target.files?.[0]; |
| 74 | + if (!file) return; |
| 75 | + |
| 76 | + const result = await upload(file); |
| 77 | + if (!result) return; // Upload failed (error shown via toast) |
| 78 | + |
| 79 | + // File uploaded successfully |
| 80 | + console.log("Public URL:", result.url); |
| 81 | + console.log("Pathname (key):", result.pathname); |
| 82 | + }; |
| 83 | + |
| 84 | + return ( |
| 85 | + <input type="file" onChange={handleFileChange} disabled={isUploading} /> |
| 86 | + ); |
| 87 | +} |
| 88 | +``` |
| 89 | + |
| 90 | +### Upload Flow |
| 91 | + |
| 92 | +#### Vercel Blob (Direct Upload) |
| 93 | + |
| 94 | +```mermaid |
| 95 | +sequenceDiagram |
| 96 | + participant Browser |
| 97 | + participant UploadURL as /api/storage/upload-url |
| 98 | + participant Vercel as Vercel Blob CDN |
| 99 | +
|
| 100 | + Browser->>UploadURL: POST (request client token) |
| 101 | + Note over Browser,UploadURL: User authenticated |
| 102 | + UploadURL->>Vercel: Generate client token |
| 103 | + Vercel-->>UploadURL: Return token |
| 104 | + UploadURL-->>Browser: Return token + URL |
| 105 | + Browser->>Vercel: PUT file (with token) |
| 106 | + Vercel-->>Browser: Upload complete |
| 107 | + Vercel->>UploadURL: Webhook: upload completed |
| 108 | + Note over UploadURL: Optional: Save to DB |
| 109 | +``` |
| 110 | + |
| 111 | +### Features |
| 112 | + |
| 113 | +- ✅ **Cloud-Based Storage**: Vercel Blob provides globally distributed CDN |
| 114 | +- ✅ **Works Everywhere**: Same storage in development and production |
| 115 | +- ✅ **Direct Client Upload**: Browser uploads directly to CDN (fastest) |
| 116 | +- ✅ **Public Access**: All files get public URLs |
| 117 | +- ✅ **Authentication**: Users must be logged in to upload |
| 118 | +- ✅ **Collision Prevention**: UUID-based file naming |
| 119 | +- ✅ **Type Safety**: Full TypeScript support with unified interface |
| 120 | + |
| 121 | +## Server-Side Upload |
| 122 | + |
| 123 | +For server-side uploads (e.g., programmatically generated files): |
| 124 | + |
| 125 | +```ts |
| 126 | +import { serverFileStorage } from "lib/file-storage"; |
| 127 | + |
| 128 | +const result = await serverFileStorage.upload(buffer, { |
| 129 | + filename: "generated-image.png", |
| 130 | + contentType: "image/png", |
| 131 | +}); |
| 132 | + |
| 133 | +console.log("Public URL:", result.sourceUrl); |
| 134 | +``` |
| 135 | + |
| 136 | +## Upload Completion Webhook |
| 137 | + |
| 138 | +The `/api/storage/upload-url` endpoint handles the `onUploadCompleted` webhook from Vercel Blob. You can add custom logic here: |
| 139 | + |
| 140 | +```ts |
| 141 | +// src/app/api/storage/upload-url/route.ts |
| 142 | + |
| 143 | +onUploadCompleted: async ({ blob, tokenPayload }) => { |
| 144 | + const { userId } = JSON.parse(tokenPayload); |
| 145 | + |
| 146 | + // Save to database |
| 147 | + await db.files.create({ |
| 148 | + url: blob.url, |
| 149 | + pathname: blob.pathname, |
| 150 | + userId, |
| 151 | + size: blob.size, |
| 152 | + contentType: blob.contentType, |
| 153 | + }); |
| 154 | + |
| 155 | + // Send notification |
| 156 | + // await sendNotification(userId, "File uploaded!"); |
| 157 | +}; |
| 158 | +``` |
| 159 | + |
| 160 | +## Advanced |
| 161 | + |
| 162 | +### Local Development with Vercel Blob Webhooks |
| 163 | + |
| 164 | +To test Vercel Blob's `onUploadCompleted` webhook locally, use [ngrok](https://ngrok.com/): |
| 165 | + |
| 166 | +```bash |
| 167 | +# Terminal 1: Start your app |
| 168 | +pnpm dev |
| 169 | + |
| 170 | +# Terminal 2: Start ngrok |
| 171 | +ngrok http 3000 |
| 172 | + |
| 173 | +# Add to .env.local |
| 174 | +VERCEL_BLOB_CALLBACK_URL=https://abc123.ngrok-free.app |
| 175 | +``` |
| 176 | + |
| 177 | +Without ngrok, uploads will work but `onUploadCompleted` won't be called locally. |
| 178 | + |
| 179 | +### Custom Storage Backend |
| 180 | + |
| 181 | +To implement a custom storage driver (e.g., Cloudflare R2, MinIO, S3): |
| 182 | + |
| 183 | +1. Create a new file in `src/lib/file-storage/` (e.g., `r2-file-storage.ts`) |
| 184 | +2. Implement the `FileStorage` interface from `file-storage.interface.ts` |
| 185 | +3. Add your driver to `index.ts` |
| 186 | +4. Update `FILE_STORAGE_TYPE` environment variable |
| 187 | + |
| 188 | +The `FileStorage` interface provides: |
| 189 | + |
| 190 | +- `upload()` - Server-side file upload |
| 191 | +- `createUploadUrl()` - Generate presigned URL for client uploads (optional) |
| 192 | +- `download()`, `delete()`, `exists()`, `getMetadata()`, `getSourceUrl()` |
| 193 | + |
| 194 | +### Storage Comparison |
| 195 | + |
| 196 | +| Feature | Vercel Blob | S3 (Planned) | |
| 197 | +| -------------------- | ------------------- | ------------------ | |
| 198 | +| Direct Client Upload | ✅ Yes | ✅ Yes (presigned) | |
| 199 | +| CDN | ✅ Global | Configurable | |
| 200 | +| Cost | Pay-as-you-go | Pay-as-you-go | |
| 201 | +| Best For | All deployments | AWS ecosystem | |
| 202 | +| Setup Complexity | Minimal | Moderate | |
| 203 | +| Local Development | ✅ Works with token | ✅ Works | |
| 204 | + |
| 205 | +## Why Not Local Filesystem? |
| 206 | + |
| 207 | +Local filesystem storage is **not supported** because: |
| 208 | + |
| 209 | +1. **AI APIs can't access localhost**: When AI APIs receive `http://localhost:3000/file.png`, they cannot fetch the file |
| 210 | +2. **Serverless incompatibility**: Platforms like Vercel don't support persistent filesystem |
| 211 | +3. **No CDN**: Files aren't globally distributed |
| 212 | + |
| 213 | +**Solution**: Vercel Blob provides a free tier and works seamlessly in both local development and production. Simply run `vercel env pull` to get your token locally. |
0 commit comments