Pushduck
Pushduck// S3 uploads for any framework
Integrations

tRPC

End-to-end typesafe file storage operations with tRPC - uploads handled by your framework!

Using pushduck with tRPC

tRPC enables end-to-end typesafe APIs with excellent TypeScript integration. With pushduck, you use tRPC for storage operations (listing, deleting, metadata) while file uploads happen through your framework's routes using pushduck handlers. This gives you the best of both worlds: framework-native uploads with type-safe storage management.

Separation of Concerns: File uploads use your framework's native upload routes with pushduck handlers, while tRPC procedures handle all storage-related CRUD operations using pushduck's storage API for full type safety.

Architecture Overview

Quick Setup

Install dependencies

npm install @trpc/server @trpc/client pushduck
# Framework-specific tRPC packages:
# @trpc/next (for Next.js)
# @trpc/react-query (for React)
yarn add @trpc/server @trpc/client pushduck
# Framework-specific tRPC packages:
# @trpc/next (for Next.js)
# @trpc/react-query (for React)
pnpm add @trpc/server @trpc/client pushduck
# Framework-specific tRPC packages:
# @trpc/next (for Next.js)
# @trpc/react-query (for React)
bun add @trpc/server @trpc/client pushduck
# Framework-specific tRPC packages:
# @trpc/next (for Next.js)
# @trpc/react-query (for React)

Configure storage and upload router

lib/storage.ts
import { createUploadConfig } from 'pushduck/server';

// Configure storage
export const { s3, storage, createS3Router } = createUploadConfig()
  .provider("cloudflareR2",{
    accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,
    region: 'auto',
    endpoint: process.env.AWS_ENDPOINT_URL!,
    bucket: process.env.S3_BUCKET_NAME!,
    accountId: process.env.R2_ACCOUNT_ID!,
  })
  .build();

// Upload router for framework routes
export const uploadRouter = createS3Router({
  imageUpload: s3.image().maxFileSize("5MB"),
  documentUpload: s3.file().maxFileSize("10MB")
});

export type AppUploadRouter = typeof uploadRouter;

Create tRPC router with storage operations

server/trpc.ts
import { initTRPC, TRPCError } from '@trpc/server';
import { z } from 'zod';
import { storage } from '~/lib/storage';

const t = initTRPC.create();

export const appRouter = t.router({
  files: t.router({
    // List files with pagination
    list: t.procedure
      .input(z.object({ 
        prefix: z.string().optional(),
        limit: z.number().min(1).max(100).default(20),
        cursor: z.string().optional()
      }))
      .query(async ({ input }) => {
        const result = await storage.list.paginated({
          prefix: input.prefix,
          maxKeys: input.limit,
          continuationToken: input.cursor,
        });
        
        return {
          files: result.files,
          nextCursor: result.nextContinuationToken,
          hasMore: result.isTruncated,
        };
      }),

    // Get file metadata
    getInfo: t.procedure
      .input(z.object({ key: z.string() }))
      .query(async ({ input }) => {
        const info = await storage.metadata.getInfo(input.key);
        if (!info.exists) {
          throw new TRPCError({ 
            code: 'NOT_FOUND', 
            message: 'File not found' 
          });
        }
        return info;
      }),

    // Get multiple files info
    getBatch: t.procedure
      .input(z.object({ keys: z.array(z.string()) }))
      .query(async ({ input }) => {
        return await storage.metadata.getBatch(input.keys);
      }),

    // Delete file
    delete: t.procedure
      .input(z.object({ key: z.string() }))
      .mutation(async ({ input }) => {
        const result = await storage.delete.file(input.key);
        return { success: result.success };
      }),

    // Delete multiple files
    deleteBatch: t.procedure
      .input(z.object({ keys: z.array(z.string()) }))
      .mutation(async ({ input }) => {
        const result = await storage.delete.files(input.keys);
        return { 
          success: result.success,
          deleted: result.deleted,
          errors: result.errors,
        };
      }),

    // Generate download URL
    getDownloadUrl: t.procedure
      .input(z.object({ 
        key: z.string(),
        expiresIn: z.number().optional()
      }))
      .query(async ({ input }) => {
        const result = await storage.download.presignedUrl(
          input.key, 
          input.expiresIn
        );
        return { url: result.url, expiresAt: result.expiresAt };
      }),

    // Search files by extension
    searchByExtension: t.procedure
      .input(z.object({ 
        extension: z.string(),
        prefix: z.string().optional()
      }))
      .query(async ({ input }) => {
        return await storage.list.byExtension(
          input.extension, 
          input.prefix
        );
      }),

    // Search files by size range
    searchBySize: t.procedure
      .input(z.object({
        minSize: z.number().optional(),
        maxSize: z.number().optional(),
        prefix: z.string().optional()
      }))
      .query(async ({ input }) => {
        return await storage.list.bySize(
          input.minSize,
          input.maxSize,
          input.prefix
        );
      }),

    // Get storage statistics
    getStats: t.procedure
      .input(z.object({ prefix: z.string().optional() }))
      .query(async ({ input }) => {
        const files = await storage.list.files({ prefix: input.prefix });
        
        const stats = files.files.reduce((acc, file) => {
          acc.totalSize += file.size;
          acc.count += 1;
          
          const ext = file.key.split('.').pop()?.toLowerCase() || 'unknown';
          acc.byExtension[ext] = (acc.byExtension[ext] || 0) + 1;
          
          return acc;
        }, {
          totalSize: 0,
          count: 0,
          byExtension: {} as Record<string, number>
        });
        
        return stats;
      }),
  }),
});

export type AppRouter = typeof appRouter;

Create framework upload route

app/api/upload/[...path]/route.ts
import { uploadRouter } from '~/lib/storage';

// Handle file uploads through framework route
export const { GET, POST } = uploadRouter.handlers;
app/routes/api.upload.$.tsx
import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";
import { uploadRouter } from "~/lib/storage";

export async function loader({ request }: LoaderFunctionArgs) {
  return uploadRouter.handler(request);
}

export async function action({ request }: ActionFunctionArgs) {
  return uploadRouter.handler(request);
}
src/routes/api/upload/[...path]/+server.ts
import type { RequestHandler } from './$types';
import { uploadRouter } from '$lib/storage';

export const GET: RequestHandler = async ({ request }) => {
  return uploadRouter.handler(request);
};

export const POST: RequestHandler = async ({ request }) => {
  return uploadRouter.handler(request);
};

Create tRPC API route

app/api/trpc/[trpc]/route.ts
import { fetchRequestHandler } from '@trpc/server/adapters/fetch';
import { appRouter } from '~/server/trpc';

const handler = (req: Request) =>
  fetchRequestHandler({
    endpoint: '/api/trpc',
    req,
    router: appRouter,
    createContext: () => ({}),
  });

export { handler as GET, handler as POST };
server/index.ts
import express from 'express';
import * as trpcExpress from '@trpc/server/adapters';
import { appRouter } from './trpc';
import { uploadRouter } from './storage';
import { toExpressHandler } from 'pushduck/adapters';

const app = express();

// tRPC for storage operations
app.use('/api/trpc', trpcExpress.createExpressMiddleware({
  router: appRouter,
  createContext: () => ({}),
}));

// pushduck for file uploads
app.all('/api/upload/*', toExpressHandler(uploadRouter.handlers));

app.listen(3000);
server/index.ts
import { createHTTPServer } from '@trpc/server/adapters/standalone';
import { appRouter } from './trpc';

// tRPC server for storage operations
const server = createHTTPServer({
  router: appRouter,
  createContext: () => ({}),
});

server.listen(3001); // Different port for tRPC

Client-Side Usage

Uploads bypass tRPC entirely — bytes go straight to storage via presigned URLs — while tRPC owns everything around them: listing, deleting, metadata, and permissions. On the client that means the pushduck hook sits alongside your tRPC hooks, and the two are joined by React Query cache invalidation.

Upload Component with Cache Invalidation

The key integration point: when an upload completes, invalidate the tRPC queries that list files, so your UI updates the same way it would after any mutation.

src/components/FileUpload.tsx
import { useUploadRoute } from "pushduck/client";
import { trpc } from "~/utils/trpc";
import type { AppUploadRouter } from "~/lib/upload";

export function FileUpload() {
  const utils = trpc.useUtils();

  const { files, progress, isUploading, uploadFiles, cancel } =
    useUploadRoute<AppUploadRouter>("imageUpload", {
      endpoint: "/api/upload",
      onSuccess: async () => {
        // Same invalidation you would run after a tRPC mutation — the upload
        // just happened over a different transport.
        await utils.files.list.invalidate();
        await utils.files.getStats.invalidate();
      },
      onError: (error) => console.error("Upload failed:", error),
    });

  return (
    <div className="space-y-4">
      <input
        type="file"
        multiple
        accept="image/*"
        disabled={isUploading}
        onChange={(e) => uploadFiles(Array.from(e.target.files ?? []))}
      />

      {isUploading && <progress value={progress} max={100} />}

      {files.map((file) => (
        <div key={file.id} className="flex gap-2 items-center">
          <span>{file.name}</span>
          <span>
            {file.status} ({file.progress}%)
          </span>
          {file.status === "uploading" && (
            <button onClick={() => cancel(file.id)}>Cancel</button>
          )}
        </div>
      ))}
    </div>
  );
}

Uploads as a Mutation

The component above lets the pushduck hook own loading and error state. If you would rather tRPC and TanStack Query own it — so uploads sit in the same isPending / onError / retry machinery as the rest of your app — use the promise-based uploadFiles instead of the hook:

src/components/UploadMutation.tsx
import { uploadFiles } from "pushduck/client";
import { useMutation } from "@tanstack/react-query";
import { trpc } from "~/utils/trpc";

export function UploadMutation() {
  const utils = trpc.useUtils();

  const { mutate: upload, isPending, error } = useMutation({
    mutationFn: (files: File[]) =>
      uploadFiles({
        files,
        route: "imageUpload",
        endpoint: "/api/upload",
        onFileStateChange: (file) => {
          // Per-file progress, if you want to render it.
          console.log(file.name, file.status, file.progress);
        },
      }),
    onSuccess: async ({ files, failedFiles }) => {
      if (failedFiles.length > 0) {
        console.warn(`${failedFiles.length} file(s) failed`);
      }
      await utils.files.list.invalidate();
    },
  });

  return (
    <>
      <input
        type="file"
        multiple
        disabled={isPending}
        onChange={(e) => upload(Array.from(e.target.files ?? []))}
      />
      {error && <p role="alert">{error.message}</p>}
    </>
  );
}

Which one should I use?

  • useUploadRoute — the hook owns per-file state, progress, speed, ETA, and cancellation. Fewest moving parts for an upload-centric UI.
  • uploadFiles + useMutation — your async-state library owns loading and errors, so uploads inherit your existing retry, error-boundary, and devtools setup. Track per-file progress yourself via onFileStateChange.

Both drive the same engine, so behaviour is identical.

Resolve vs. reject

uploadFiles distinguishes two kinds of failure, which is what makes it behave correctly under useMutation:

OutcomeResult
Batch could not run — auth rejected, route missing, network downRejects with UploadBatchError, so onError fires and retries apply
Some files failed, others succeededResolves with { files, failedFiles }

Partial failure resolves deliberately: those bytes are already in storage, and throwing would discard the successful uploads along with the failed ones.

Upload and Manage Together

A file browser that uploads through pushduck and manages through tRPC:

src/components/FileManager.tsx
import { useUploadRoute } from "pushduck/client";
import { trpc } from "~/utils/trpc";

export function FileManager() {
  const utils = trpc.useUtils();

  const { data: files, isLoading } = trpc.files.list.useQuery({});

  const deleteFile = trpc.files.delete.useMutation({
    onSuccess: () => utils.files.list.invalidate(),
  });

  const { uploadFiles, isUploading, progress } = useUploadRoute("imageUpload", {
    endpoint: "/api/upload",
    onSuccess: () => utils.files.list.invalidate(),
  });

  if (isLoading) return <p>Loading…</p>;

  return (
    <div>
      <input
        type="file"
        multiple
        disabled={isUploading}
        onChange={(e) => uploadFiles(Array.from(e.target.files ?? []))}
      />
      {isUploading && <progress value={progress} max={100} />}

      <ul>
        {files?.map((file) => (
          <li key={file.key}>
            {file.key}
            <button
              onClick={() => deleteFile.mutate({ key: file.key })}
              disabled={deleteFile.isPending}
            >
              Delete
            </button>
          </li>
        ))}
      </ul>
    </div>
  );
}

Two routers, by design. You export AppRouter (tRPC) and AppUploadRouter (pushduck) separately. tRPC is JSON-RPC and cannot carry binary bodies or report upload progress, so routing files through it would mean base64-encoding them and losing progress, cancellation, and direct-to-S3 transfer. The two systems stay parallel and meet at the cache.

Optimistic UI

Because files from the hook already carries per-file status and progress, you usually do not need optimistic updates for the upload itself — render the hook's state during the upload and the invalidated tRPC query afterwards.

Authentication Integration

This is where the two systems most need to agree. tRPC derives the user in createContext; pushduck's middleware receives the raw Request. Write the resolver once and call it from both — otherwise your auth rules drift apart.

One Resolver, Two Consumers

src/server/auth.ts
/**
 * Single source of truth for "who is making this request".
 * Consumed by tRPC's context and by pushduck's upload middleware.
 */
export async function getUserFromRequest(req: Request) {
  const authHeader = req.headers.get("authorization");
  if (!authHeader?.startsWith("Bearer ")) return null;

  try {
    return await validateToken(authHeader.substring(7));
  } catch {
    return null;
  }
}
src/server/trpc.ts
import { initTRPC, TRPCError } from "@trpc/server";
import { getUserFromRequest } from "./auth";

export const createContext = async ({ req }: { req: Request }) => ({
  user: await getUserFromRequest(req),
});

type Context = Awaited<ReturnType<typeof createContext>>;
const t = initTRPC.context<Context>().create();

const isAuthenticated = t.middleware(({ next, ctx }) => {
  if (!ctx.user) throw new TRPCError({ code: "UNAUTHORIZED" });
  return next({ ctx: { ...ctx, user: ctx.user } });
});

export const protectedProcedure = t.procedure.use(isAuthenticated);
export const router = t.router;
src/lib/upload.ts
import { getUserFromRequest } from "~/server/auth";

const uploadRouter = s3.createRouter({
  imageUpload: s3
    .image()
    .maxFileSize("5MB")
    // The same resolver tRPC uses — one place to change auth rules.
    .middleware(async ({ req }) => {
      const user = await getUserFromRequest(req);
      if (!user) throw new Error("Unauthorized");

      return {
        userId: user.id,
        // Never trust client-provided identity claims; derive them here.
        role: user.role,
      };
    })
    .paths({
      // Scope uploads to the same prefix your tRPC procedures enforce.
      prefix: ({ metadata }) => `users/${metadata.userId}`,
    }),
});

export type AppUploadRouter = typeof uploadRouter;
export const { GET, POST } = uploadRouter.handlers;

Keep the path prefix and your tRPC procedures' ownership checks in sync. If uploads land in users/{id}/ then files.list and files.delete must scope to that same prefix, or a user will be able to read or delete another user's objects.

Reusing tRPC Procedures in onUploadComplete

When an upload finishes you usually want to write a database row — logic that probably already exists as a tRPC procedure. Use createCaller to invoke it server-side instead of duplicating it:

src/lib/upload.ts
import { appRouter } from "~/server/routers/_app";

const uploadRouter = s3.createRouter({
  imageUpload: s3
    .image()
    .middleware(async ({ req }) => {
      const user = await getUserFromRequest(req);
      if (!user) throw new Error("Unauthorized");
      return { userId: user.id, user };
    })
    .onUploadComplete(async ({ file, metadata }) => {
      // Same procedure your client calls — one implementation, one set of
      // validation rules, called with an authenticated context.
      const caller = appRouter.createCaller({ user: metadata.user });

      await caller.files.record({
        key: file.key,
        name: file.name,
        size: file.size,
        contentType: file.type,
      });
    }),
});

createCaller is tRPC's server-side invocation API. It runs the procedure's input validation and middleware exactly as an HTTP call would, so business rules cannot drift between the upload path and the API path.

Scoped Storage Procedures

src/server/routers/files.ts
import { z } from "zod";
import { TRPCError } from "@trpc/server";
import { storage } from "~/lib/storage";
import { protectedProcedure, router } from "../trpc";

export const filesRouter = router({
  list: protectedProcedure
    .input(z.object({ prefix: z.string().optional() }))
    .query(async ({ input, ctx }) => {
      // Same prefix convention the upload router writes to.
      const userPrefix = `users/${ctx.user.id}/${input.prefix ?? ""}`;
      return storage.list.files({ prefix: userPrefix });
    }),

  delete: protectedProcedure
    .input(z.object({ key: z.string() }))
    .mutation(async ({ input, ctx }) => {
      if (!input.key.startsWith(`users/${ctx.user.id}/`)) {
        throw new TRPCError({ code: "FORBIDDEN" });
      }
      return storage.delete.file(input.key);
    }),

  record: protectedProcedure
    .input(
      z.object({
        key: z.string(),
        name: z.string(),
        size: z.number(),
        contentType: z.string(),
      })
    )
    .mutation(async ({ input, ctx }) => {
      return db.file.create({ data: { ...input, userId: ctx.user.id } });
    }),
});

Real-time Updates with Subscriptions

server/trpc.ts
import { observable } from '@trpc/server/observable';
import { EventEmitter } from 'events';

const fileEventEmitter = new EventEmitter();

export const appRouter = t.router({
  files: t.router({
    // ... other procedures

    // Real-time file updates
    onUpdate: protectedProcedure
      .subscription(({ ctx }) => {
        return observable<{ type: 'uploaded' | 'deleted'; file: any }>((emit) => {
          const onFileEvent = (data: any) => {
            // Only emit events for this user's files
            if (data.userId === ctx.user.id) {
              emit.next(data);
            }
          };
          
          fileEventEmitter.on('file:event', onFileEvent);
          
          return () => {
            fileEventEmitter.off('file:event', onFileEvent);
          };
        });
      }),
  }),
});

// Emit events from upload completion
export const emitFileEvent = (type: 'uploaded' | 'deleted', file: any, userId: string) => {
  fileEventEmitter.emit('file:event', { type, file, userId });
};

Performance Benefits

Type Safety

Full TypeScript support for all storage operations

Optimistic Updates

Fast UI updates with automatic rollback on errors

Efficient Queries

React Query integration with caching and deduplication

Real-time Sync

WebSocket subscriptions for live file updates

Key Advantages

Clear Separation

  • Uploads: Framework-native routes with pushduck handlers
  • Storage Operations: Type-safe tRPC procedures with pushduck storage API
  • Client: Framework upload hooks + tRPC queries/mutations

Best of Both Worlds

  • Framework-optimized uploads (progress, validation, middleware)
  • Type-safe storage management (list, delete, search, metadata)
  • Unified developer experience with consistent patterns

Scalable Architecture

  • Independent scaling of upload and API operations
  • Flexible deployment (separate services if needed)
  • Framework agnostic storage operations

Troubleshooting

Common Issues

  1. Mixed responsibilities: Don't try to handle uploads in tRPC procedures - use framework routes
  2. Type mismatches: Ensure storage operations use the same config as upload routes
  3. Authentication: Sync auth between upload middleware and tRPC context
  4. CORS: Configure CORS for both /api/trpc and /api/upload endpoints

Debug Mode

lib/debug.ts
// Enable debug logging for both systems
export const debugConfig = {
  trpc: process.env.NODE_ENV === 'development',
  storage: process.env.NODE_ENV === 'development',
};

// Storage debug logging
export const storage = createStorage(config).middleware?.(async (operation, params) => {
  if (debugConfig.storage) {
    console.log("Storage operation:", operation, params);
  }
});

// Upload debug logging  
export const uploadRouter = createS3Router({
  // ... routes
}).middleware(async ({ req, file }) => {
  if (debugConfig.storage) {
    console.log("Upload request:", req.url);
    console.log("File:", file.name, file.size);
  }
  return {};
});

This architecture gives you framework-native file uploads with type-safe storage management, combining the strengths of both pushduck and tRPC for a superior developer experience.