Upload and serve media
Configure S3 storage, upload assets from the browser, and serve them.
This guide uploads and serves assets. It assumes a CMS instance (see Quickstart) and an S3-compatible bucket. For the model behind it, see Media.
Configure storage
createCMS requires a media config: your bucket plus a public base URL (a CDN domain). The full shape is in the configuration reference:
media: {
provider: 'cloudflare',
accountId: process.env.R2_ACCOUNT_ID!,
bucketName: process.env.R2_BUCKET!,
accessKeyId: process.env.R2_KEY!,
secretAccessKey: process.env.R2_SECRET!,
publicUrl: process.env.R2_PUBLIC_URL!,
},Upload from the browser
The React client's media.useUploadAssets() returns an upload function plus a ledger of every file handed to it. Under the hood it requests signed URLs and PUTs each file straight to your bucket, at most four at a time:
'use client';
import { cmsClient } from '@/lib/cms-client';
export function Uploader() {
const { upload, isUploading, progress, files, reset } =
cmsClient.media.useUploadAssets();
return (
<>
<input
type="file"
multiple
onChange={async (e) => {
const entries = await upload(Array.from(e.target.files ?? []));
const ids = entries.flatMap((entry) =>
entry.status === 'success' && entry.result ? [entry.result.id] : [],
);
console.log('uploaded', ids);
}}
/>
{isUploading ? (
<p>Uploading {Math.round(progress.fraction * 100)}%</p>
) : null}
<ul>
{files.map((entry) => (
<li key={entry.id}>
{entry.name}: {entry.status}
{entry.error ? ` (${entry.error.code})` : null}
</li>
))}
</ul>
<button type="button" onClick={reset}>
Clear finished
</button>
</>
);
}upload(files, options?) takes a File[] and an optional { folderId, concurrency, signal }. It resolves with that call's entries once every PUT has settled, so a caller reads result.id from the returned array instead of scanning files. Uploads are validated server-side against the limits (defaults: maxFiles 10, maxFileSize 4 MB, allowedMimeTypes an explicit image/video/PDF allowlist that excludes SVG, see Configuration); a rejected batch marks every entry of that call error with the server code (FILE_TOO_LARGE, TOO_MANY_FILES, or INVALID_FILE_TYPE). A PUT that fails on the network is NETWORK_ERROR; any other PUT failure is UPLOAD_FAILED. New assets are created private.
| Field | Type | Description |
|---|---|---|
upload | (files: File[], options?: CMSMediaUploadOptions) => Promise<CMSMediaUploadFileState[]> | Start an upload; resolves with that call's entries. Options: folderId, concurrency (max parallel PUTs, default 4), signal (aborts this call only). |
isUploading | boolean | true while any entry is pending or uploading. |
progress | { loaded, total, fraction } | Bytes uploaded over bytes expected across pending, uploading, and success entries; fraction is 0 to 1. error and aborted entries are excluded. |
files | CMSMediaUploadFileState[] | Every entry handed to upload since the last reset(), in call order. Each has id, file, name, size, type, status (pending, uploading, success, error, aborted), loaded, total, progress (0 to 1), error? ({ code, message }), and result? ({ id, slug, objectKey }). |
error | unknown | The signing error, or 'Some files failed to upload' when a PUT failed. null otherwise. |
abort | () => void | Aborts every in-flight and pending entry; they end aborted, not error. |
reset | () => void | Drops success, error, and aborted entries and clears error; in-flight entries stay. |
Optimize before upload
Add the media optimize plugin to resize, compress, and convert images in the browser before handing them to upload — see Media optimize → Usage.
Serve an asset
Serve assets through the CMS gate: GET /media/asset/{id}, a public redirect to the object, addressed by the asset id (which is exactly what content stores). Use this in content and on public pages — it enforces status (a private asset returns ASSET_ACCESS_DENIED; flip one to public with updateAssetsStatus) and honors ?format= and ?w= by resolving a pre-uploaded variant asset (falling back to the original). There is no on-the-fly transform: produce variants ahead of time (for example with the optimize plugin).
<img src="https://your-cms.example.com/media/asset/ast_6t4x5a98n2io352uhbkq" />listAssets and the upload responses also return a direct url per asset — your publicUrl joined with the asset's objectKey. It bypasses the gate (no status check, no transforms, ignores query strings), so it is for internal tooling like a media-library admin UI showing thumbnails of assets you manage — not for embedding in content:
const thumb = asset.url; // direct object URL — admin/library display only
// e.g. https://cdn.example.com/welcome-heroUpload from the server
For server-initiated uploads, call the API directly. createSignedUpload returns presigned PUT URLs and a token per file (you PUT the bytes with the returned headers, then pass the tokens to completeUpload, which creates the rows); uploadAssets sends the bytes through the server (each file needs a buffer: Blob | ArrayBuffer):
const { uploads } = await cms.api.media.createSignedUpload({
body: { files: [{ name: 'hero.jpg', size: file.size, type: 'image/jpeg' }] },
});
await fetch(uploads[0].signedUrl, {
method: 'PUT',
headers: uploads[0].headers,
body: file,
});
const { assets, errors } = await cms.api.media.completeUpload({
body: { uploads: [{ token: uploads[0].token }] },
});For the asset model, folders, and private vs public, see Media.