@everystack/storage
v0.2.0
Published
File uploads via S3 + CloudFront CDN with presigned URLs
Downloads
280
Readme
@everystack/storage
File upload handler with pluggable storage backends (filesystem, S3), presigned URLs, validation, and upload metadata tracking via Drizzle ORM.
Install
pnpm add @everystack/storage drizzle-ormFor S3 storage:
pnpm add @aws-sdk/client-s3 @aws-sdk/s3-request-presignerEntry Points
| Import | Description |
|--------|-------------|
| @everystack/storage | Handler, adapters, validation |
| @everystack/storage/schema | Drizzle uploads table |
| @everystack/storage/client | Client-side presigned URL helpers |
Quick Start
import { createStorageHandler, createObjectStorage } from '@everystack/storage';
import { db } from './db';
const storage = createObjectStorage({
type: 's3',
bucket: 'my-uploads',
region: 'us-east-1',
cdnUrl: 'https://cdn.example.com',
});
const handler = createStorageHandler({
db,
storage,
basePath: '/api/storage',
auth: {
verifyToken: async (token) => verifyJWT(token),
},
validation: {
maxSize: 10 * 1024 * 1024, // 10MB
allowedTypes: ['image/jpeg', 'image/png', 'image/webp'],
},
});Mounting as an Expo Router API Route
// app/api/storage/[...path]+api.ts
export function GET(request: Request) { return handler(request); }
export function POST(request: Request) { return handler(request); }
export function DELETE(request: Request) { return handler(request); }Handler Endpoints
| Method | Path | Description |
|--------|------|-------------|
| POST | /presign | Get a presigned upload URL |
| POST | /upload | Direct multipart file upload |
| GET | /files/:key | Download a file (or redirect to presigned URL) |
| GET | /uploads | List upload metadata (paginated) |
| GET | /uploads/:id | Get upload metadata |
| DELETE | /uploads/:id | Delete upload + file |
Presigned Upload Flow
// 1. Client requests presigned URL
const res = await fetch('/api/storage/presign', {
method: 'POST',
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'photo.jpg', type: 'image/jpeg', size: 1024000 }),
});
const { url, key } = await res.json();
// 2. Client uploads directly to S3
await fetch(url, { method: 'PUT', body: file, headers: { 'Content-Type': 'image/jpeg' } });
// 3. Use the `key` to reference the fileDirect Upload
const formData = new FormData();
formData.append('file', file);
const res = await fetch('/api/storage/upload', {
method: 'POST',
headers: { Authorization: `Bearer ${token}` },
body: formData,
});
const { id, key } = await res.json();Handler Options
interface StorageHandlerOptions {
db: DrizzleDb;
storage: ObjectStorageAdapter;
basePath?: string;
bucket?: string; // Logical bucket name for metadata (default: 'default')
auth?: {
verifyToken: (token: string) => Promise<Record<string, unknown> | null>;
};
allowUnauthenticated?: boolean; // Explicit opt-in for public uploads (default: false)
validation?: {
maxSize?: number; // Max file size in bytes
allowedTypes?: string[]; // MIME types (e.g., ['image/jpeg', 'image/png'])
allowedExtensions?: string[]; // File extensions (e.g., ['.jpg', '.png'])
};
presignedUrlExpiry?: number; // Presigned URL lifetime in seconds (default: 3600)
keyGenerator?: (file: { name: string; type: string; userId?: string }) => string;
publishJob?: (type: string, payload: unknown) => Promise<string>;
}Authentication Requirement
When auth is not configured, all endpoints return 401 by default — the handler is secure by default. To explicitly allow unauthenticated uploads (e.g., public file drops), set allowUnauthenticated: true.
// Secure: all endpoints require auth
const handler = createStorageHandler({ db, storage, auth: { verifyToken } });
// Secure: explicit public access
const handler = createStorageHandler({ db, storage, allowUnauthenticated: true });
// Secure: no auth configured → all requests get 401
const handler = createStorageHandler({ db, storage });Ownership Enforcement
When auth is configured, the storage handler enforces file ownership:
- DELETE
/uploads/:id— only the user who uploaded the file can delete it. Returns403ifuserIddoesn't match. - GET
/uploads/:id— only the owner can read upload metadata. Returns403ifuserIddoesn't match. - GET
/files/:key— serves the file (ownership checked via metadata lookup).
This prevents users from deleting or accessing other users' uploads even if they know the upload ID.
MIME Type Validation
When validation.allowedTypes is configured, the handler validates uploads at two levels:
- Client-declared type — the
Content-Typeheader ortypefield is checked against the allowlist. - Magic-byte verification — the first bytes of the file are inspected to detect the actual file type. If the declared MIME type doesn't match the detected type, the upload is rejected with
400.
This prevents attacks where a malicious file is uploaded with a spoofed Content-Type header (e.g., uploading an executable as image/jpeg).
Presigned URL Expiry
Configure how long presigned upload/download URLs remain valid:
const handler = createStorageHandler({
db, storage,
presignedUrlExpiry: 900, // 15 minutes (default: 3600 = 1 hour)
});
### Custom Key Generator
```typescript
const handler = createStorageHandler({
db,
storage,
keyGenerator: ({ name, type, userId }) => {
const ext = name.split('.').pop();
return `users/${userId}/${crypto.randomUUID()}.${ext}`;
},
});Image Processing Integration
Wire storage uploads to @everystack/jobs for automatic image processing:
import { createJobClient, PostgresJobAdapter } from '@everystack/jobs';
const jobClient = createJobClient(new PostgresJobAdapter(db));
const handler = createStorageHandler({
db,
storage,
publishJob: (type, payload) => jobClient.publish(type, payload),
});
// Image uploads automatically publish a 'process-image' jobStorage Adapters
Filesystem
import { createObjectStorage } from '@everystack/storage';
const storage = createObjectStorage({
type: 'filesystem',
directory: './uploads',
baseUrl: 'http://localhost:3000/files',
});S3
const storage = createObjectStorage({
type: 's3',
bucket: 'my-app-uploads',
region: 'us-east-1',
endpoint: 'https://s3.us-east-1.amazonaws.com', // Optional custom endpoint
cdnUrl: 'https://cdn.example.com', // Optional CDN prefix
});Custom Adapter
Implement the ObjectStorageAdapter interface:
interface ObjectStorageAdapter {
put(key: string, data: Buffer | Uint8Array, contentType?: string): Promise<void>;
get(key: string): Promise<{ data: Buffer; contentType: string } | null>;
exists(key: string): Promise<boolean>;
list(prefix: string): Promise<string[]>;
delete(key: string): Promise<void>;
deleteMany?(keys: string[]): Promise<void>;
getPresignedUploadUrl?(key: string, contentType: string, expiresIn?: number): Promise<string>;
getPresignedDownloadUrl?(key: string, expiresIn?: number): Promise<string>;
}Schema
Add the uploads table to your Drizzle migrations:
import { uploads } from '@everystack/storage/schema';
// Use in your Drizzle schema alongside your app tablesThe uploads table tracks: id, key, bucket, contentType, size, originalName, metadata, userId, createdAt.
Peer Dependencies
| Package | Version | Required |
|---------|---------|----------|
| drizzle-orm | >=0.30.0 | Yes |
| @aws-sdk/client-s3 | >=3.0.0 | For S3 adapter |
| @aws-sdk/s3-request-presigner | >=3.0.0 | For S3 presigned URLs |
Part of everystack — a self-hosted application stack for Expo apps on AWS.
License
MIT
