Skip to content

Storage

Declare buckets in your schema, point file and image fields at them, and upload through the client. Who may read, upload, overwrite and delete is decided by Postgres from the bucket’s rules.

Pre-1.0: APIs and config may change between releases.

Declare a bucket

A bucket is a type alias for Bucket<"id", { ... }> in your schema. The schema page has the short version. Every key in the second argument is optional.

schema/index.ts
import type { Bucket, BucketLoggedIn, BucketOwner, BucketRole } from "@supatype/types"
export type Attachments = Bucket<"attachments", {
accessMode: "private"
accept: ["application/pdf", "image/*"]
maxSize: "20MB"
access: {
read: BucketOwner
create: BucketLoggedIn
update: BucketOwner
delete: BucketRole<"admin">
}
}>
KeyWhat it does
accessMode"public", "private" or "custom". Defaults to "private". Only "public" serves files on a public URL. "custom" reads like "private" and is for buckets that set s3BucketPolicy.
maxSizeLargest file accepted, written as "500KB", "20MB" or "1GB". Units are B, KB, MB and GB, counted in 1024s. Anything else fails the push.
acceptContent types the bucket takes. Exact types such as "image/png", or a wildcard such as "image/*". Leave it out to accept any type.
accessThe read, create, update and delete rules, covered below. Any other key fails the push.
s3BucketPolicyA raw S3 bucket policy as a JSON string, applied to the object store bucket in place of the default. It needs an S3 bucket per bucket, so single-bucket mode never applies it: there one policy would cover every bucket at once. It is applied exactly as written, so its Resource names the S3 bucket, which is S3_BUCKET_PREFIX then the bucket’s id: with the prefix acme-prod-, the bucket avatars needs arn:aws:s3:::acme-prod-avatars/*.

supatype push and supatype dev register each bucket and write its settings. Changing maxSize, accept or accessMode and pushing again updates the bucket. Declaring the same bucket id twice with different settings fails the push.

File and image fields

ImageAsset<Bucket> and FileAsset<Bucket> are fields that point at a file in a bucket. The column is JSONB holding the bucket and the path, and the generated type is StorageReference:

supatype/generated
export type StorageReference = {
bucket: string
path: string
}

The field stores a reference, not the file. Upload the file first, then write its path to the row:

const path = `${userId}/${file.name}`
const { error: uploadError } = await supatype.storage.from("attachments").upload(path, file)
if (uploadError) throw new Error(uploadError.message)
await supatype.from("post").update({ attachment: { bucket: "attachments", path } }).eq("id", postId)
  • Always name the bucket. Without one, ImageAsset points at a bucket called images and FileAsset at one called assets, and neither exists unless you declare it.
  • ImageAsset<Covers, { localized: true }> stores one reference per locale instead of one.
  • Deleting a row does not delete its file, and deleting a file does not clear the field.

Access rules

Each rule becomes a row level security policy on the table that records every stored file. The storage service runs each upload, overwrite, delete and list as the caller, so Postgres decides, the same way it does for your models.

RuleWho passes
BucketPublicEveryone, including the anon key
BucketLoggedInAny signed-in user
BucketOwnerThe user who uploaded the file. An overwrite keeps the original owner.
BucketRole<"admin">Users whose app_metadata.role is admin, the same check as Role on a model
BucketPrivateNobody but the service role
  • A rule you leave out is refused, and the push prints a warning naming it.
  • update and delete need a read rule beside them. Postgres only lets a caller change rows it can read, so without one they match nothing. The push warns about this too, even on a public bucket.
  • accessMode: "public" serves files on the public URL without asking the read rule. Writes still go through create, update and delete.
  • list returns only the files the caller may read. remove deletes only the files the caller may delete, leaves the rest in place and returns just the ones it removed.
  • A refused write answers 401 to the anon key, because signing in might change the answer, and 403 to a signed-in user.

Upload

The client page shows the basic calls. upload sends the file in one request with the caller’s token.

const { data, error } = await supatype.storage.from("attachments").upload(`${userId}/slides.pdf`, file, {
contentType: "application/pdf",
upsert: false,
})
if (error) console.error(error.status, error.message)

file may be a File, a Blob or an ArrayBuffer. On success data is { path }.

Without contentType the client uses the File’s own type. If that is missing or generic, the service guesses from the extension (.png, .pdf, .mp4 and other common types). The type is checked against accept before anything is stored.

With upsert: true an existing file at that path is replaced if the update rule allows it. The new bytes are stored alongside the old ones and swapped in when the row commits, so a reader never sees a half-written file.

StatusWhy
401, 403The bucket’s create rule (or update, for an overwrite) refused the caller
404No bucket with that id
409A file already exists at that path and upsert was not set
413The file is larger than the bucket’s maxSize, or the service limit when there is none
415The content type is not in accept. The body lists the allowed types.
507The upload would take the project past its total storage quota

Download and URLs

There are three ways to read a file. All three go through the storage service, which looks up the file’s current version, so a URL keeps working after the file is overwritten.

MethodPathWho can use it
getPublicUrl(path)/storage/v1/object/public/…Anyone, only on a bucket with accessMode: "public". Builds the URL locally with no request.
download(path)/storage/v1/object/authenticated/…The caller, if the read rule allows. Returns a Blob.
createSignedUrl(path, seconds)/storage/v1/object/sign/…?token=Anyone holding the link until it expires

A signed URL is only issued to a caller the read rule allows, and only for a file that exists. The expiry must be between 1 second and 7 days. The token is signed by the storage service and covers one bucket and one path. createSignedUrls(paths, seconds) signs several paths and reports an error per path.

const bucket = supatype.storage.from("attachments")
const { data: blob } = await bucket.download(`${userId}/slides.pdf`)
const { data: link } = await bucket.createSignedUrl(`${userId}/slides.pdf`, 3600)
const { data: files } = await bucket.list(`${userId}/`, { limit: 50, offset: 0 })

list returns up to 100 entries unless you pass limit. Each entry has name, size, mimetype, the owner and timestamps.

The first argument to list is a folder. Folders inside it come first, then files, each in name order, and there is no sort option. Pass search to match names without regard to case. The result also carries count, the number of matching entries in all.

How long a file may be cached depends on how it was read. There is no setting per upload.

Read throughCache-Control
getPublicUrl, on a public bucketpublic, max-age=3600
download, with the user’s sessionprivate, no-store. No cache keeps it, so a CDN never serves one user’s file to another.
A signed URLpublic, with a max-age of 3600 or the seconds left on the link, whichever is less. A cached copy stops when the link does.

Every other answer, including an error such as a 404, carries Cache-Control: no-store. A CDN never keeps “not found” for a file you upload a moment later.

Public and private buckets differ in CORS too. A public bucket answers any origin. A private bucket sends no Access-Control-Allow-Origin, so read its files from a browser with a signed URL or download.

storage.listBuckets() and storage.createBucket(name, { public, fileSizeLimit, allowedMimeTypes }) need the service role key. Use them from a server or script, not a browser. In an app, declare buckets in the schema instead. The client has no call to change or delete a bucket. To change one, edit its declaration and push.

Image transforms

getPublicUrl and download take a transform option. The service resizes and re-encodes the image on each request.

const { data: { publicUrl } } = supatype.storage.from("covers").getPublicUrl(post.cover.path, {
transform: { width: 800, height: 450, resize: "cover", format: "avif", quality: 70 },
})
OptionValuesDefault
width, height1 to 4096 pixelsthe original size
resizecover, contain, fill, inside, outsidecover
formatwebp, avif, png, jpegwebp
quality1 to 10080
  • A transform runs only when width, height, format or quality is set. resize on its own does nothing.
  • Any transform re-encodes the image, as WebP unless you set format.
  • Images are never enlarged past their original size.
  • Files whose type is not image/* are served unchanged.
  • The same query parameters (width, height, resize, format, quality) work when appended to a signed URL.
  • On a public bucket, transformed responses carry Cache-Control: public, max-age=3600 by default, set by TRANSFORM_CACHE_TTL. Put a CDN in front if the same sizes are requested often.
  • A transform read with the user’s session is private, no-store, and one through a signed URL is cached no longer than the link lasts, as for plain files.

Limits and config

The storage service reads these environment variables. The self-host compose file sets the database, JWT and object store ones for you. The rest keep their defaults unless you set them on the storage service.

VariableDefaultWhat it controls
TIER_MAX_UPLOAD_SIZE52428800 (50 MB)Largest file, in bytes, for a bucket with no maxSize. A bucket’s maxSize always wins.
STORAGE_QUOTA1073741824 (1 GB)Total bytes across every bucket. An upload past it gets 507.
MAX_SIGNED_URL_EXPIRY604800 (7 days)Longest signed URL, in seconds
DEFAULT_SIGNED_URL_EXPIRY3600Expiry when a signing request names none
SIGNED_URL_SECRETthe JWT secretKey that signs URL tokens. Changing it invalidates every signed URL.
TRANSFORM_CACHE_TTL3600max-age, in seconds, on transformed images
S3_BUCKETunsetOne S3 bucket that holds every bucket as a key prefix, as described below. Unset, each bucket gets an S3 bucket of its own, which the service creates and names S3_BUCKET_PREFIX then the bucket’s id.
S3_BUCKET_PREFIXemptyWith S3_BUCKET unset, put in front of each bucket’s id to name its S3 bucket: acme-prod- makes avatars the S3 bucket acme-prod-avatars. S3 bucket names are global on AWS, so set one there. A prefix or a bucket id that makes no valid S3 bucket name is refused, the prefix at start and the bucket with 400.
S3_KEY_PREFIXemptyWith S3_BUCKET set, a folder every key goes under, so several storage services can share one S3 bucket: abc123/production keeps avatars/cat.png at abc123/production/avatars/cat.png. One to four folder names joined by /, each lowercase letters, digits, - and _. Bucket ids are then limited to letters, digits, ., _ and -. Anything else is refused, the prefix at start and the bucket with 400.
S3_ENDPOINT, S3_REGION, S3_ACCESS_KEY, S3_SECRET_KEY, S3_FORCE_PATH_STYLEnoneWhere the bytes are kept. The self-host stack sets them for its SeaweedFS. Running the service yourself, set S3_REGION for AWS or S3_ENDPOINT for another store; the service refuses to start with neither. Leave both keys blank to use the AWS SDK’s own credentials. Path-style addressing is on when there is an endpoint.

The service reads each upload fully into memory before storing it, so very large files cost memory on the storage container while they upload.

Where files live

File metadata is a row in the storage schema of your project’s Postgres. The bytes go to an S3-compatible object store, each upload under its own versioned key. Read files through the storage API, not the object store, because the key is not the path you uploaded to.

Where you runWhere the bytes go
supatype dev (Docker, the default for new projects)A SeaweedFS container, in the storage-data Docker volume. Its port is not published to your machine. supatype dev --reset-db keeps it.
supatype dev with provider: "native"Files under ~/.supatype/projects/<name>/storage-service, served by the storage service running on your machine
supatype dev with provider: "native" and storage: { provider: "s3" }Your own S3 bucket, named by S3_BUCKET in .env, served by the storage service running on your machine
supatype self-host compose up with storage: { production: "s3" }Your own S3 bucket, named by S3_BUCKET in the server’s .env. The stack runs no SeaweedFS. See self-hosting configuration.
supatype self-host compose upA SeaweedFS service in the stack, in the storage-data volume. Its S3 port, 8333, is published (SUPATYPE_SEAWEEDFS_PORT changes it) and needs the stack’s credentials. There is no anonymous access.

Switching storage or GraphQL off

services: { storage: false } in supatype.config.ts answers every /storage/v1 request with 503, and services: { graphql: false } answers /graphql/v1 with 501. Self-host renders SUPATYPE_STORAGE_DISABLED and SUPATYPE_GRAPHQL_DISABLED into the server; a push to Supatype Cloud sets the same switch for the project. A key left out leaves the service on, and true turns it back on.

Your own S3 bucket

On Supatype Cloud, name the bucket in supatype.config.ts and supatype push (or supatype deploy) sends it to the project’s production environment. Only the organisation’s owners and admins can set it, and the keys are read from your environment or .env with env("NAME"), sent once, stored encrypted and never shown again:

supatype.config.ts
import { defineConfig, env } from "@supatype/cli"
export default defineConfig({
// docs:no-check (a fragment: the rest of your config stays as it is)
storage: {
provider: "s3",
production: "s3",
s3: { bucket: "acme-files", region: "eu-west-1", accessKey: env("ACME_S3_KEY"), secretKey: env("ACME_S3_SECRET") },
},
})

Use endpoint (an https URL) in place of region for another S3-compatible store, and forcePathStyle to override path-style addressing. Both keys are required on Cloud, since a Cloud project has no instance role to fall back to. Leaving storage.s3 out of the config sends nothing and keeps whatever the project has; to go back to Supatype’s bucket, call DELETE /projects/<ref>/storage-bucket.

Set S3_BUCKET and the storage service keeps every bucket inside that one S3 bucket, the way Supabase Storage uses GLOBAL_S3_BUCKET. A bucket is a row in your database and a key prefix in S3: a file avatars/me.png is stored under avatars/me.png/<version>. The service never creates an S3 bucket or puts a bucket policy, so:

  • The S3 bucket stays private. Public files are served by the storage service at /storage/v1/object/public/<bucket>/<path>, never straight from S3.
  • The keys only need to read, write, list and delete objects in that one bucket (s3:GetObject, s3:PutObject, s3:DeleteObject and s3:ListBucket on AWS). They do not need to create buckets.
  • Deleting a bucket deletes every key under its prefix.
StoreSet
AWS S3S3_BUCKET and S3_REGION. Leave S3_ENDPOINT blank. Leave S3_ACCESS_KEY and S3_SECRET_KEY blank to use the AWS SDK’s own credentials, such as an instance or task role or AWS_PROFILE.
Another S3-compatible store, such as Cloudflare R2S3_BUCKET, S3_ENDPOINT, S3_ACCESS_KEY and S3_SECRET_KEY. S3_REGION defaults to us-east-1 and path-style addressing is on; set S3_FORCE_PATH_STYLE=false if your store wants the bucket in the host name.

The service refuses to start without either S3_REGION or S3_ENDPOINT, or with only one of the two keys. Use a separate bucket for development and production.

In a self-hosted stack the storage service runs in a container, where localhost is that container. For a store on the same machine, such as a MinIO you run beside the stack, set S3_ENDPOINT to an address the container can reach: http://host.docker.internal:9000 with Docker Desktop on macOS and Windows, or on Linux the host’s address on the Docker bridge (usually http://172.17.0.1:9000) or its LAN address. Native supatype dev runs the service on your machine, so localhost works there.

A bucket’s s3BucketPolicy needs an S3 bucket of its own, so single-bucket mode never applies it. The storage service refuses one with 400 on a bucket made or changed through its API. A bucket supatype push creates keeps the policy in its record without applying it, and nothing warns you yet. If you need a policy per bucket, leave S3_BUCKET unset so each bucket gets its own S3 bucket, and set S3_BUCKET_PREFIX to keep their names unique.

Setting S3_BUCKET on a storage service that already holds files does not move them: they stay in the per-bucket S3 buckets the service made before, where it no longer looks.

With storage: { provider: "s3" }, native supatype dev starts the storage service against the bucket in .env, and stops with a message if S3_BUCKET is blank. A SUPATYPE_STORAGE_URL in .env still wins: dev then starts no storage service and sends storage requests to that URL.

Back up the storage-data volume along with the database. A database dump holds the file records but not the bytes.

Removing a bucket from the schema drops its policies on the next push. The bucket and its files stay where they are.