Assets
Centralized asset management split across three built-in entities by content type.
Assets are stored across three built-in entities — _image, _video, and _file — each with only the fields relevant to its type. All uploads go through a single endpoint and are routed automatically by MIME type.
Built-in entities
_image
| Field | Type | Required | Notes |
|---|---|---|---|
id |
auto | yes | UUID primary key |
filename |
text | yes | Original filename |
mimeType |
text | yes | e.g. image/jpeg, image/png |
size |
number | no | File size in bytes |
width |
number | no | Extracted via sharp |
height |
number | no | Extracted via sharp |
alt |
text | no | Alt text for accessibility |
url |
text | yes | Storage URL |
_video
| Field | Type | Required | Notes |
|---|---|---|---|
id |
auto | yes | UUID primary key |
filename |
text | yes | Original filename |
mimeType |
text | yes | e.g. video/mp4, video/webm |
size |
number | no | File size in bytes |
width |
number | no | Reserved for future metadata extraction |
height |
number | no | Reserved for future metadata extraction |
url |
text | yes | Storage URL |
_file
| Field | Type | Required | Notes |
|---|---|---|---|
id |
auto | yes | UUID primary key |
filename |
text | yes | Original filename |
mimeType |
text | yes | e.g. application/pdf |
size |
number | no | File size in bytes |
url |
text | yes | Storage URL |
Uploading files
All uploads go to a single endpoint. The file is routed to the correct entity based on its MIME type. Uploading needs create on that entity (_image, _video or _file), for a public role too.
POST /api/assets/upload
Content-Type: multipart/form-data
file: <binary>
alt: "Description of the image" (optional, only stored for images)
Large images
An image wider than 3840 px (the widest transform) is resized to 3840 px wide at upload and stored in place of the uploaded file, so transforms never decode a photography-grade original. The stored image:
- keeps the upload’s format (JPEG at quality 95 with full colour resolution, PNG lossless, WebP and AVIF at quality 95);
- is upright, with the EXIF orientation applied to its pixels;
- has no EXIF metadata (GPS location, camera serial), and keeps its colour profile.
The record’s width, height and size describe the stored image. Its hash is the uploaded file’s, so uploading the same file again still returns the existing record. SVGs, animated images and TIFF or GIF files are stored as uploaded, as are images uploaded before this was introduced.
Change the cap, or keep every upload as-is, in cms.config:
export default config({
// ...
assets: {
image: { maxWidth: 2560 }, // or `false` to store originals
},
});
MIME type routing
| MIME pattern | Entity |
|---|---|
image/* |
_image |
video/* |
_video |
| Everything else | _file |
The mapping is by MIME type, not by behavior — SVGs and animated GIFs are treated as images.
Response — image
{
"data": {
"id": "uuid",
"filename": "photo.jpg",
"mimeType": "image/jpeg",
"size": 245000,
"width": 1920,
"height": 1080,
"alt": "Description of the image",
"url": "/api/assets/abc123.jpg",
"createdAt": "2025-06-01T00:00:00Z",
"updatedAt": "2025-06-01T00:00:00Z"
}
}
Image dimensions are extracted automatically via sharp for JPEG, PNG, WebP, AVIF, TIFF, and GIF. They are the upright dimensions: a portrait phone photo stored sideways with an EXIF orientation tag reports its portrait width and height. SVGs and unreadable images will have null dimensions.
Response — video
{
"data": {
"id": "uuid",
"filename": "intro.mp4",
"mimeType": "video/mp4",
"size": 8200000,
"url": "/api/assets/def456.mp4",
"createdAt": "2025-06-01T00:00:00Z",
"updatedAt": "2025-06-01T00:00:00Z"
}
}
Response — file
{
"data": {
"id": "uuid",
"filename": "report.pdf",
"mimeType": "application/pdf",
"size": 120000,
"url": "/api/assets/ghi789.pdf",
"createdAt": "2025-06-01T00:00:00Z",
"updatedAt": "2025-06-01T00:00:00Z"
}
}
Image transforms
Uploaded images can be transformed on-the-fly by adding query parameters to the file URL:
GET /api/assets/abc123.jpg?w=400&format=webp
GET /api/assets/abc123.jpg?w=800&fit=cover&format=avif&q=75
Parameters
| Param | Description | Default |
|---|---|---|
w |
Width in pixels (snapped to nearest allowed breakpoint). Height is calculated from aspect ratio. | Original |
fit |
Resize strategy: cover, contain, fill, inside, outside |
cover |
format |
Output format: webp, avif, jpeg, png |
webp |
q |
Quality (1–100), snapped to the nearest of 50, 65, 80, 90 |
80, snapped like a given q |
Width is snapped to the nearest standard breakpoint (16, 32, 48, 64, 96, 128, 256, 384, 640, 750, 828, 1080, 1200, 1920, 2048, 3840) and quality to the nearest configured step, so arbitrary values don’t bust the cache. Images are never enlarged beyond their original dimensions.
Any other query parameter, a parameter given twice, and a format, fit, w or q value outside the ones above, returns 400. Cache-busting suffixes like ?v=2 are rejected too.
Transforms are upright: an EXIF orientation tag is applied to the pixels, so a photo shows the same way transformed as the browser shows the original.
Public responses (originals and transforms) are served with Cache-Control: public, max-age=31536000, immutable plus a strong ETag, and Access-Control-Allow-Origin: * with no Vary: Origin — so a CDN caches a single variant per URL. Put a CDN in front and transforms are cached at the edge after the first request — no server-side caching needed. Conditional requests (If-None-Match) get a 304 without re-running the transform.
Private assets are served with Cache-Control: private, no-store — they never land in a shared cache.
Transform limits
Each transform decodes and re-encodes the image, so a page full of uncached variants can saturate a small machine. The engine bounds the work per process:
- At most
concurrencytransforms run at once; the rest wait for a slot. - A request that doesn’t get a slot within
queueTimeoutMsgets the original image, withCache-Control: public, max-age=0, s-maxage=60and the original’sETag. The CDN keeps it for a minute, then fetches the transformed variant once the burst has drained. - An image with more than
maxInputPixelspixels is served untransformed, with the usual year-long cache.
Every limit has a default sized for a single shared vCPU, so a project sets nothing unless it wants a different value:
| Option | Default | Effect |
|---|---|---|
concurrency |
2 |
Transforms at once per process. A positive integer |
queueTimeoutMs |
5000 |
How long a transform waits for a slot before the original is served. An integer of at least 0 |
qualities |
[50, 65, 80, 90] |
?q= snaps to the nearest, and so does the default 80 when q is omitted. Integers from 1 to 100 |
maxInputPixels |
50_000_000 |
Larger inputs are served untransformed. A positive integer |
avifEffort |
2 |
AVIF encoder effort, 0 (fastest) to 9 |
Set only the options you change; the rest keep their defaults. On a machine with more cores, for example:
export default config({
// ...
assets: {
image: { transform: { concurrency: 4 } },
},
});
An invalid value throws when the config loads.
AVIF encoding dominates transform CPU. At effort 2 a photo encodes several times faster than at sharp’s default of 4, for a file within a few percent of the size. Raise avifEffort only if bandwidth matters more than CPU.
A request whose client disconnects while it waits for a slot leaves the queue without running. Each transform logs an Image transformed line with its waitMs and encodeMs, and each fallback logs Image transform queue full. Use them to tune concurrency and queueTimeoutMs.
Without any query parameters, the original file is served as-is.
Transforms apply to images only (_image). Video and file URLs are served as-is, and so are animated GIF, WebP and AVIF images: a transform would keep only the first frame.
Deduplication
Files are deduplicated by SHA-256 hash, checked within the same entity. Uploading the same image twice returns the existing _image record instead of creating a duplicate. If you upload a duplicate with a different alt, the alt text is updated on the existing record, which needs update on _image.
The existing record comes back only when the uploader’s read on the entity reaches it. When it doesn’t (no read, or a read filter that excludes the record), the upload is a 409 that returns nothing of it.
Deduplication is scoped to the target entity — the same binary uploaded as an image and then as a file would create two separate records.
Referencing assets
Use the typed field helpers in your entity config:
import { entity, text, image, video, file } from "@cms/config";
const posts = entity("posts", {
fields: [
text("title", { required: true }),
image("featuredImage"),
image("gallery", { multiple: true }),
video("demoVideo"),
file("attachment"),
file("downloads", { multiple: true }),
],
});
For fields that accept multiple asset types, use a polymorphic relation directly:
import { relation } from "@cms/config";
relation("media", { to: ["_image", "_video"] })
In the admin UI, image(), video(), and file() fields automatically render typed upload inputs with preview, browse, and remove controls.
Reading assets through a relation
An asset is a document of _image, _video or _file, and resolving a relation to it is a read of that entity with the requester’s role. A role that can’t read the asset entity gets the relation back unresolved, as a bare { id, _entity } reference, with no error. So a site reading with the public role (or an API key’s role) needs read on every asset entity its relations point to:
role("public", {
public: true,
permissions: {
posts: { read: { filter: { status: "published" } } },
_image: { read: true },
_video: { read: true },
_file: { read: true },
},
});
cms dev keeps serving the config it started with, so restart it after changing a role. See Permissions.
Storage
storage is required and takes a provider: the code that stores and returns asset files. The CMS keeps everything else — asset rows, storage keys, URLs, resizing and transforms — so switching providers changes where the bytes live and nothing else. There is no default: a project picks one explicitly, so uploads never land on a disk nobody meant to keep.
Local disk
localDisk() ships in @cms/config and writes files to a directory.
import { config, localDisk } from "@cms/config";
export default config({
storage: localDisk({ root: "./uploads" }),
// ...
});
| Option | Required | Description |
|---|---|---|
root |
yes | Directory for asset files, absolute or relative to the working directory. Created if missing |
Use it for development and single-node deployments where the process owns the disk. In a container, mount root on a volume — otherwise uploads disappear with the container while their rows stay in Postgres. It doesn’t suit clustered deployments: nodes don’t share the disk.
S3
@cms/storage-s3 stores assets in any S3-compatible service — AWS S3, MinIO, Cloudflare R2, Backblaze B2.
pnpm add @cms/storage-s3
import { config } from "@cms/config";
import { s3 } from "@cms/storage-s3";
export default config({
storage: s3({
bucket: process.env.S3_BUCKET,
region: process.env.S3_REGION,
accessKeyId: process.env.S3_ACCESS_KEY_ID,
secretAccessKey: process.env.S3_SECRET_ACCESS_KEY,
// Optional: custom endpoint for non-AWS services (MinIO, R2, etc.)
endpoint: process.env.S3_ENDPOINT,
}),
// ...
});
| Option | Required | Description |
|---|---|---|
bucket |
yes | S3 bucket name |
region |
yes | AWS region, e.g. us-east-1 |
accessKeyId |
no | Access key ID. Omit with secretAccessKey to use the AWS credential chain |
secretAccessKey |
no | Secret access key. Omit with accessKeyId to use the AWS credential chain |
endpoint |
no | Custom endpoint URL for S3-compatible services. Enables path-style addressing |
bucket and region take process.env values as they are: a missing or empty one stops
cms start and cms dev from booting, while cms build never needs them. Supply both
credential fields or neither — supplying only one is a configuration error and the engine
refuses to start. Read them from process.env: cms.config is
bundled into the admin, so a literal value would ship to the browser.
Credential chain
Omit accessKeyId and secretAccessKey and the SDK resolves credentials from the
environment instead: an EC2 instance role, an ECS task role, a Kubernetes service
account federated via OIDC (IRSA on EKS, AWS_WEB_IDENTITY_TOKEN_FILE elsewhere),
a CI job’s OIDC token, or a local SSO session.
Prefer this over static keys. The workload itself is authorized to reach the bucket, the credentials it gets are short-lived and rotated automatically, and there is no shared secret to distribute or store. Static key pairs should be the exception — see Storage credentials for the per-environment breakdown.
export default config({
storage: s3({
bucket: process.env.S3_BUCKET,
region: process.env.S3_REGION,
// no credentials — resolved from the instance/task role
}),
// ...
});
Grant the role s3:PutObject, s3:GetObject, and s3:DeleteObject on
arn:aws:s3:::<bucket>/*. S3-compatible services that aren’t AWS S3 — MinIO, R2,
B2 — implement the API but not the credential chain, so they still need a key pair.
Writing a provider
A provider is a plain object (types from @cms/config, unstable until 1.0):
type StorageProvider = {
/** Shown in the boot log: `Storage: <description>`. */
description: string;
/** Called once at boot, in Node only. */
create: () => ObjectStore | Promise<ObjectStore>;
};
type ObjectStore = {
upload(key: string, data: Buffer, mimeType: string): Promise<void>;
getBuffer(key: string): Promise<Buffer>; // rejects when the key is missing
delete(key: string): Promise<void>; // resolves when the key is missing
};
Keys are <asset id>.<extension>. The CMS never asks a provider for a URL: every asset is served from /api/assets/<key>.
cms.config is also bundled into the admin, so put the code create runs — and the SDK it loads — in a *.server.ts module. The admin build replaces it with a stub, the same rule as server-only code:
// gcs-storage.ts
import type { StorageProvider } from "@cms/config";
import { createGcsStore } from "./gcs-store.server";
export const gcs = (options: { bucket: string | undefined }): StorageProvider => ({
description: "gcs",
create: () => createGcsStore(options.bucket),
});
Check required options in create, never in the factory: the factory also runs in cms build and
the admin bundle, where process.env is empty. A throw from create stops the boot, and the engine
reports it together with every other missing option and variable.
Serving
All asset URLs are served through the CMS API (/api/assets/{key}) whatever the storage provider. The CMS fetches files from storage on demand and handles all transforms. Public responses are served with Cache-Control: public, max-age=31536000, immutable and a strong ETag — put a CDN (CloudFront, Cloudflare, etc.) in front and it will cache at the edge after the first request. Private assets are served with Cache-Control: private, no-store and are never cached at the edge.
Cleaning up unused assets
Replacing an image or deleting an entry leaves the old asset behind. The cleanup finds assets nothing references and deletes them from the library and from storage. Run it from Assets → Clean up unused in the admin: it lists what it would delete, with the count and total size, and deletes nothing until you confirm.
An asset counts as in use if any entry points to it through an image, video, file or other relation, in the entry itself, in a pending draft, or in a version kept in history. The check matches UUIDs wherever they sit, including inside rich text and blocks, so it may keep an asset that is unused but never deletes one that is in use.
- Grace period. An asset created less than an hour ago is never deleted, so a file uploaded for an entry that isn’t saved yet is safe.
- Permission. Only admins and roles with
assets: { cleanup: true }can run it. See Permissions. - Safety. Each row is deleted in its own transaction, which checks the references again. An asset referenced since the preview is kept. The one exception is a reference inside a JSON field (a block or rich text) saved in the instant between that check and the commit, which isn’t guarded. The stored object is removed after the commit, as with a single delete.
- Audit. Every run is written to the log with the count, the size and the deleted ids, and each deleted asset gets a
deleteentry in the audit log. No hooks or observers run.
GET /api/assets/cleanup/unused # dry run: { assets, count, totalSize }
POST /api/assets/cleanup # body: { "ids": [...] } — deletes those of them still unused
Querying assets
Each asset type is a regular entity and can be queried like any other:
GET /api/_image?filter[mimeType][$startsWith]=image/png&sort=-createdAt&limit=20
GET /api/_video?sort=-createdAt
GET /api/_file?filter[mimeType]=application/pdf
Resolved asset relations return full records:
GET /api/posts?resolve[featuredImage]=*
Previous
Emails
Next
Internationalization