Skip to content

Building blocks

Storage

Uploaded files live in R2, under one policy per purpose: user avatars, organization photos, and whatever you add. You work here when you accept a new kind of upload, change a size limit or a format, serve files only to their owner, or hold photos back until they are checked.

How it works

  1. A purpose in storage.purposes names the R2 binding and bucket, the formats it accepts, its size cap, who may read it, and its Cache-Control.
  2. Your upload route calls readUpload, which checks the size and sniffs the file's first bytes, then newObjectKey and putObject, then writes the key to your row.
  3. A key is <purpose>/<owner>/<32 hex>.<ext>, where the owner is a user id, or an account's or an organization's public id on a purpose whose ownerSegment says so. layers/kit/modules/storage-routes.ts(Licensees only) registers GET /api/<purpose>/:owner/:file for every purpose, so objectSrc(key) is just /api/ plus the key.
  4. To replace a file, store the new one, point the row at it, then deleteObject the old one.

The shipped purposes are avatars and org-avatars. Both use the AVATARS binding and bucket, both are public, and both declare ownerSegment: 'public-id'. PUT /api/auth/avatar writes the first and PUT /api/orgs/:org/avatar the second, until account.avatarUpload or orgs.avatarUpload switches them off. avatars keys a photo by the account's public id, which userPublicId mints at the account's first upload, and org-avatars by the organization's public id. While auth and account.avatarUpload are on, the build refuses a config without avatars, or with it but without that ownerSegment. org-avatars is needed only while organizations are on; with orgs.enabled true, the build refuses a config without it, or with it but without that ownerSegment.

Add a purpose

Add an entry to storage.purposes in starter.config.ts(Licensees only). An invoice store that only the uploader can read:

invoices: {
  binding: 'INVOICES',
  bucket: 'my-app-invoices',
  formats: ['pdf'],
  maxBytes: 10 * 1024 * 1024,
  noun: 'invoice',
  access: 'owner',
  cacheControl: 'private, no-store',
},

Bind the bucket in wrangler.jsonc(Licensees only):

"r2_buckets": [
  { "binding": "AVATARS", "bucket_name": "nuxter-avatars" },
  { "binding": "INVOICES", "bucket_name": "my-app-invoices" },
],

Then regenerate the Env types, create the bucket before you deploy, and restart pnpm dev:

pnpm cf-typegen
pnpm exec wrangler r2 bucket create my-app-invoices

The purpose id is the key prefix, the URL segment and the config key at once, so it must match /^[a-z][a-z0-9-]*$/. pnpm dev and the build refuse a purpose whose binding wrangler.jsonc doesn't declare, or whose bucket differs from the one that binding points at. Locally, R2 runs in Wrangler's simulator and needs no bucket.

Accept an upload

The client posts multipart/form-data with the file in a field named file:

const body = new FormData()
body.append('file', file)

await $fetch('/api/invoices', { method: 'POST', body })

The route, server/api/invoices.post.ts:

import {
  deleteObject,
  newObjectKey,
  putObject,
  readUpload,
} from '#layers/kit/server/storage'
import { objectSrc } from '#layers/kit/shared/utils/storage'

export default defineEventHandler(async (event) => {
  const session = await requireVerifiedSession(event)

  const upload = await readUpload(event, 'invoices')
  const key = newObjectKey('invoices', session.user.id, upload.format)

  await putObject(event, 'invoices', key, upload)

  try {
    await useDrizzle(event)
      .insert(tables.acmeInvoices)
      .values({ userId: session.user.id, key })
  } catch (error) {
    await deleteObject(event, 'invoices', key)
    throw error
  }

  return { src: objectSrc(key) }
})

tables.acmeInvoices is your own table in server/database/schema.ts, its name prefixed with your app's (Database).

readUpload throws before anything is stored:

Statusdata.reasonWhenExtra data
400upload-missingNo non-empty file part
413upload-too-largeContent-Length or the file is over maxBytesmaxBytes
415upload-formatThe first bytes match none of the purpose's formatsformats

Word the refusal from data in the reader's language. The English statusMessage is built from the policy for logs: noun: 'invoice' gives "Choose an invoice up to 10 MB." and "Use a PDF invoice."

putObject stores the object with the sniffed format's Content-Type and fires storage:uploaded (Events). A failed put throws, so your row is never written for an object that isn't there.

Replace or delete a file

deleteObject(event, purpose, key, replacing?) never throws. A failed delete is swallowed and leaves the object in the bucket; only a delete that happened fires storage:deleted. It does nothing when key is empty or equals replacing, which protects the object the row points at now.

When two uploads can race, make the row write a compare-and-set on the key you read first, as layers/kit/server/auth/routes/avatar.put.ts(Licensees only) does:

const swapped = await useDrizzle(event)
  .update(tables.acmeInvoices)
  .set({ key })
  .where(
    and(
      eq(tables.acmeInvoices.id, invoiceId),
      eq(tables.acmeInvoices.key, previous),
    ),
  )
  .returning({ id: tables.acmeInvoices.id })

if (swapped.length === 0) {
  await deleteObject(event, 'invoices', key)

  throw createError({ statusCode: 409, statusMessage: 'Reload and try again.' })
}

await deleteObject(event, 'invoices', previous, key)

With a plain update, the losing upload's object is referenced by nothing and never cleaned up.

Hold uploads for review

storage:uploaded fires once the object is stored and already servable, and a listener can't refuse it. To scan or review a profile photo before anyone else sees it, switch the kit's upload off and take the upload yourself, into a purpose only the uploader can read:

'held-avatars': {
  binding: 'AVATARS',
  bucket: 'nuxter-avatars',
  formats: ['jpg', 'png', 'webp'],
  maxBytes: 2 * 1024 * 1024,
  noun: 'image',
  access: 'owner',
  cacheControl: 'private, no-store',
},

It reuses the AVATARS binding and bucket, so wrangler.jsonc needs no edit. Restart pnpm dev after adding it. Then:

  1. Set account.avatarUpload to false.
  2. Write your upload route in server/api/ under a path the kit doesn't use, such as server/api/profile-photo.put.ts. Never /api/auth/avatar: turn the key back on and both routes claim it.
  3. In it, call readUpload(event, 'avatars'), so the photo is checked against the policy it will be served under, then newObjectKey and putObject into held-avatars, then enqueue a scan job carrying the key (Background jobs).
  4. When the scan passes, copy the object into avatars with putObject under newObjectKey('avatars', await userPublicId(event, userId), format), since that purpose's read route serves only a public id there. userPublicId comes from #layers/kit/server/auth/public-id, and mints the account's public id the first time it is asked. Compare-and-set users.avatar on the key you read first, as avatar.put.ts(Licensees only) does, then deleteObject the replaced photo and the held copy. When the scan fails, delete the held copy.

The key unmounts DELETE /api/auth/avatar too, so removing a photo is a route of yours as well.

Account erasure deletes only the object users.avatar names. Erase held photos from a job you enqueue on account:purged, since a listener's throw is swallowed (Events). Their keys start with held-avatars/<userId>/. Delete them through the AVATARS binding rather than deleteObject, which swallows a failure, so a failed delete throws and the job retries.

An organization photo takes the same steps with orgs.avatarUpload, org-avatars and organizations.avatar. Mint its held key with the uploader's user id, never the organization's public id, because owner reads that segment as a user id. On a pass, put the copy into org-avatars under newObjectKey('org-avatars', scope.publicId, format), since that purpose's read route serves only a public id there, and swap it in with swapOrgAvatar from #layers/kit/server/tenancy/orgs, as the kit's route does: it matches only an open organization and records the change on its audit trail.

Serve files

The read route checks the path first: the owner segment must have the shape the purpose's ownerSegment names, digits for 'user-id' and 16 lowercase letters and digits for 'public-id', and the file must be 32 hex characters plus one of the purpose's own extensions. Anything else answers 404 without reading the bucket.

  • access: 'public' serves the object to anyone who has the URL, with no database read. The 32 random hex characters are what keep it unguessable.
  • access: 'owner' needs a verified session whose account the key's owner segment names. A signed-out request gets 401 and another user gets 404, so nobody learns the object exists. The response is always private, no-store, whatever cacheControl says.

owner compares the owner segment with the session's publicId on a purpose whose ownerSegment is 'public-id', and with the session's user id on any other, so an owner-only avatars serves each photo to its own account. org-avatars keys carry the organization's public id, which never equals an account's, so while organizations are on the build refuses access: 'owner' on that purpose. To stop accepting organization photos, set orgs.avatarUpload to false.

Responses carry a Content-Type from the file's extension and a Content-Length from R2. The route ignores Range and always answers 200 with the whole object. Chrome and Firefox play audio and video from it but can't seek without refetching. Safari may refuse media without a 206. serveObject in layers/kit/server/storage/serve.ts(Licensees only) is imported by path and can't be replaced, so serve media to Safari from a route of your own that answers Range.

Formats

A purpose's formats name the kit's formats, in STORAGE_FORMATS in layers/kit/shared/storage/formats.ts(Licensees only), or your own. Each has the Content-Type, the label refusals use, and the byte check:

FormatContent-TypeRecognized by
jpgimage/jpegFF D8 FF
pngimage/pngThe 8-byte PNG signature
webpimage/webpRIFF then WEBP at byte 8
pdfapplication/pdf%PDF-
mp3audio/mpegID3, or an MPEG frame sync

To accept another, declare it in storage.formats, named by the file extension it is stored under, with the byte runs that identify it at their offsets from the start:

storage: {
  formats: {
    zip: {
      mime: 'application/zip',
      label: 'ZIP',
      signature: [{ offset: 0, bytes: [0x50, 0x4b, 0x03, 0x04] }],
    },
  },
  purposes: { /* … a purpose with formats: ['zip'] */ },
},

A file matches when every run is there. The build refuses an id that is not lowercase letters and digits, one that repeats a kit format, a Content-Type a browser would run as a page or a script, and a signature with no byte runs. UNSUPPORTED_BY_DESIGN lists the ones the kit leaves out and the build refuses as ids: SVG carries script that would run on your origin, GIF isn't needed by anything shipped, DOCX and XLSX start with the same bytes as any ZIP file, and plain text has no signature to sniff.

Avatars in the browser

AvatarDropzone.vue checks a picked file with imageFileSchema(purpose) from layers/kit/shared/schemas/profile.ts(Licensees only), which reads the size and types from the same purpose through imagePolicy(purpose). That throws when storage.purposes doesn't declare the purpose. The server checks both again and sniffs the bytes.

SettingsAvatarUpload renders nothing while account.avatarUpload is off, and OrgsAvatarField nothing while orgs.avatarUpload is. A component of yours that replaces either must carry that v-if over. AvatarDropzone also works as the picker for your own route: it emits upload with a file that passed the check, and remove, and leaves the request to you.

The avatars block in layers/kit/app/app.config.ts(Licensees only) makes UAvatar render a plain <img>. Through @nuxt/image the URL would go to an optimizer that can't read /api/avatars/**, and every avatar would fall back to initials, which UAvatar builds from alt.

Configuration

Each entry in storage.purposes:

FieldShipped for both purposesWhat it does
binding'AVATARS'The R2 binding in wrangler.jsonc.
bucket'nuxter-avatars'The bucket that binding points at. Errors print the create command.
formats['jpg', 'png', 'webp']Accepted formats, checked against the first bytes.
maxBytes2 * 1024 * 1024Largest file accepted.
noun'image'What English refusal messages call the file.
access'public''public' or 'owner'.
ownerSegment'public-id''user-id', the default, or 'public-id': what the owner segment holds.
cacheControl'public, max-age=31536000, immutable'Sent on public reads. Ignored for owner.

Two keys outside storage switch the kit's photo uploads:

KeyShippedWhat it does
account.avatarUploadtrueOff unmounts PUT and DELETE /api/auth/avatar and hides the profile photo control.
orgs.avatarUploadtrueOff unmounts PUT and DELETE /api/orgs/:org/avatar and hides the photo field on the organization's General page.

Neither removes a purpose or its read route, so stored photos stay served.

There are no environment variables. The binding is the whole credential.

Good to know

  • immutable in cacheControl is safe only because every upload gets a fresh key. Never write to an existing key under that header.
  • Uploads are read into memory whole. That suits files of a few megabytes, not hundreds; a large-file purpose needs its own streaming route.
  • Nothing sweeps orphaned objects. A failed delete leaks the object, and on a public purpose it stays reachable at its URL.
  • Switching account.avatarUpload or orgs.avatarUpload off on a live deploy takes nothing down: stored photos stay served at their URLs, and nobody can remove theirs in the app any more. Clear them yourself by setting the column to null and deleting the objects. For profile photos, access: 'owner' on avatars also works, but then everyone except a photo's owner sees initials, in a blog byline drawn from an account too. org-avatars can't be owner-only while organizations are on.
  • The read route serves only keys shaped the way newObjectKey builds them, with the owner segment the purpose names, and a key whose owner segment isn't a number reports ownerId: 0 in the storage events. An account's or an organization's photo events therefore carry 0; the public id is the second segment of key. Build keys with newObjectKey.
  • flags.purpose names the purpose whose bucket the r2 feature-flag driver reads (Feature flags).

A link with a lock opens the kit’s private repository, which every licensee can read.