Skip to Content

Add File Uploads

Presigned uploads that are size- and type-checked, confirmed after arrival and scoped to each user.

Install

npm i @dapplelight/signet-server @dapplelight/signet-ui

Create the upload service

server/uploads.ts
import { supabaseBlobStore } from "@dapplelight/signet-server/adapters/supabase"
import { createUploads } from "@dapplelight/signet-server/storage"
import type { Env } from "./env"
import { makeThumbnail } from "./jobs"

export const uploadsFor = (env: Env) =>
  createUploads({
    store: supabaseBlobStore({ url: env.SUPABASE_URL, serviceRoleKey: env.SUPABASE_KEY, bucket: "avatars" }),
    maxBytes: 5_000_000,
    allowedTypes: ["image/png", "image/jpeg", "image/webp"],
    afterUpload: (u) => makeThumbnail.enqueue({ key: u.key }),
  })

Issue a presigned URL and confirm

server/routes/avatar.ts
import { app } from "../app"
import { uploadsFor } from "../uploads"

app.post("/api/avatar/presign", async (c) => {
  const userId = c.get("session").sub
  const { name, type, size } = await c.req.json()
  const { url, key } = await uploadsFor(c.env).presignUpload({ userId }, { name, type, size })
  return c.json({ url, key })
})

app.post("/api/avatar/confirm", async (c) => {
  const userId = c.get("session").sub
  const { key } = await c.req.json()
  await uploadsFor(c.env).confirmUpload({ userId }, key) // re-checks what arrived, deletes it if bad
  return c.body(null, 204)
})

Put the file from the browser

app/avatar.tsx
import { Upload } from "@dapplelight/signet-ui/domain/upload"

Or by hand: fetch(url, { method: "PUT", body: file, headers: { "Content-Type": type } }), then call confirm.

Stores that cannot presign

server/routes/avatar.ts
app.post("/api/avatar", async (c) => {
  const userId = c.get("session").sub
  const uploads = uploadsFor(c.env)
  const result = await uploads.acceptUpload({ userId }, c.req.raw) // streams, stops at maxBytes, sniffs magic bytes
  return c.json(result)
})

fsBlobStore and an R2 binding throw PRESIGN_UNSUPPORTED. acceptUpload also strips EXIF and GPS from images.

A renamed file or an oversize file is refused with an UploadError carrying its HTTP status (415, 413).

Next