Send blob (image) from frontend to backend with nextjs and trpc (T3 stack) – Trpc

by
Ali Hasan
gpt3 next.js react-typescript trpc.io zod

Quick Fix: It’s not recommended to send blobs via tRPC. Instead, use presigned URLs to upload large files to storage. Consider using UploadThing or directly using S3/R2.

The Problem:

T3 Stack File Upload: In a Next.js and TRPC (T3 stack) application, a user is unable to transfer a blob (image) from the frontend to the backend. The blob is generated using the leaflet-simple-map-screenshoter library and needs to be sent for PDF generation on the backend. Despite trying various methods like base64 encoding and ArrayBuffer, the request header becomes too large or the blob is not transferred correctly. Seeking solutions to efficiently handle blob transfer within the T3 stack.

The Solutions:

Solution 1: Use Presigned URLs

You should use presigned URLs to send large files to storage rather than sending blobs via tRPC. Presigned URLs provide a secure way to upload files directly to cloud storage, bypassing the limitations of sending large blobs through tRPC. Consider using a service like UploadThing or S3/R2 for this purpose.

Solution 2: Use Next.js 13 API routes

To allow file uploads, a new route must be established in src/app/api/. This route will specifically handle the file uploads, while the remaining application functionality will continue to utilize tRPC.

This alternative provides greater control over the flow and enables image processing. However, it also results in increased bandwidth usage.

Refer to the following Stack Overflow thread for a detailed example: https://stackoverflow.com/questions/62411430/post-multipart-form-data-to-serverless-next-js-api-running-on-vercel-now-sh/77353442#77353442

Q&A

Is it possible to send blobs via tRPC?

No, sending blobs via tRPC is not recommended.

What is the recommended way to send large files to storage with the T3 stack?

Use presigned URLs or direct S3/R2 integration.

Can you elaborate on the solution using pre-signed URLs?

Upload the image directly to S3 via a presigned URL, then update database records through a tRPC procedure.

Video Explanation:

The following video, titled "How I added S3 Image Uploads to my Next.js App (using tRPC ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Sharing how i setup an s3 bucket to allow users to upload images to a secured s3 bucket and display those secured images on the page.