npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@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-orm

For S3 storage:

pnpm add @aws-sdk/client-s3 @aws-sdk/s3-request-presigner

Entry 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 file

Direct 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. Returns 403 if userId doesn't match.
  • GET /uploads/:id — only the owner can read upload metadata. Returns 403 if userId doesn'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:

  1. Client-declared type — the Content-Type header or type field is checked against the allowlist.
  2. 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' job

Storage 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 tables

The 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