Skip to content

Media Library

The admin panel includes a media library for uploading, renaming, replacing, and deleting media files. It holds any kind of file, in folders nested as deeply as you like, on every backend. Images and videos get thumbnails, and images, videos and audio files play in the preview.

The repository library is always there. An object store can be configured beside it, and each library then gets its own entry in the admin’s sidebar. Every library decides for itself which files it takes, so small assets like SVG logos can be kept in the repository while large photos go to the store.

astro.config.ts
cms({
media: {
repo: {
allowedExtensions: [".svg", ".png", ".ico"],
maxFileSize: 1_000_000,
},
s3: {
bucket: "my-media",
endpoint: "https://s3.eu-central-1.amazonaws.com",
publicUrl: "https://cdn.example.com",
allowedExtensions: [".jpg", ".png", ".webp", ".avif", ".mp4"],
minFileSize: 500_000,
},
},
});

The size bounds may overlap, as above: the editor picks the library, and the bounds only refuse what does not belong there. A refused upload names the other library when that one would take the file.

Every library takes these:

Option Type Default Description
label string translated The library’s name in the admin’s sidebar and picker
allowedExtensions string[] any file Restricts the library to these extensions, e.g. [".svg", ".png"]
minFileSize number none Smallest upload in bytes, refused by the admin and again by the server
maxFileSize number see below Largest upload in bytes, refused by the admin and again by the server
optimizeImages ImageOptimizationConfig | false enabled How an image is reshaped in the browser before it is uploaded to this library

The repository library (media.repo) adds directory (default "src/assets") and prune. Its maxFileSize defaults to 100 MiB, the largest file GitHub accepts, while the object store has none, except for its devDirectory in astro dev, whose uploads also pass through the CMS route. The object store (media.s3) is described in Where files are stored.

The size is checked against the file as it is uploaded, so after image optimization where that is enabled. Replacing a file is checked the same way, so a replacement outside the library’s bounds is refused.

A library accepts any file unless its allowedExtensions restricts it. Hidden files (.DS_Store, .gitkeep) are never listed. A file’s content type comes from its extension, and one no registry can name is stored as a generic download. The admin serves images, videos and audio with their own type and everything else as a generic download, all under a sandboxing content security policy, so an uploaded file can neither run as a page nor be loaded as a script. An object store gets HTML, SVG and other XML documents with Content-Disposition: attachment.

Uploads land in the folder you have open, and New folder opens one that does not exist yet. Neither a repository nor an object store keeps an empty directory, so a new folder exists once its first file is uploaded. Renaming a file to 2026/summer/hero.png moves it into that folder.

Images are reshaped in the browser before they are uploaded, so a 12 MP phone original never enters the library at full size. By default an image is scaled to fit 2048x2048 and re-encoded if it exceeds 8 MB, keeping its own format.

astro.config.ts
cms({
media: {
repo: {
optimizeImages: {
maxWidth: 1600,
maxHeight: 1600,
format: "webp",
quality: 0.85,
},
},
},
});

Only formats a browser can decode and encode are touched (JPEG, PNG, WebP, AVIF). SVG, GIF, documents and any image already inside every limit are uploaded byte for byte. Each library has its own settings, and optimizeImages: false turns it off for that library, which is what you want when editors upload masters an object store is meant to hold.

See ImageOptimizationConfig for every option.

The repository library is a directory in your repository. Uploads are commits on the same draft branch as content, so an image and the entry that uses it publish together, and discarding a draft takes both back.

An object store beside it is what you want when some media outgrows the repository: large or numerous files, editors uploading originals, or assets you would rather keep out of Git. Content stores each of its files as its public URL under publicUrl, which astro resolves as a remote image by itself.

astro.config.ts
cms({
media: {
s3: {
bucket: "my-media",
endpoint: "https://s3.eu-central-1.amazonaws.com",
region: "eu-central-1",
publicUrl: "https://cdn.example.com",
},
},
});

Works with AWS S3, MinIO, Backblaze B2, Hetzner and anything else speaking the S3 API. Add forcePathStyle: true for a store that addresses objects as <endpoint>/<bucket>/<key>. Set region for a store whose endpoint does not name it and that rejects the us-east-1 fallback.

  1. Set the credentials on the server

    On the server:

    Terminal window
    ASTRONAUT_CMS_S3_ACCESS_KEY_ID=...
    ASTRONAUT_CMS_S3_SECRET_ACCESS_KEY=...
    # optional, for temporary credentials
    ASTRONAUT_CMS_S3_SESSION_TOKEN=...

    They are read by the CMS server alone and never reach the browser.

  2. Decide how the library is read, and set publicUrl to match

    Content stores public URLs, so a signed, expiring URL can never be written into an entry. publicUrl is the base the library’s keys are served from. See Reading the library for the three ways to provide one, including keeping the bucket itself closed.

    Whatever serves it must not share an origin with the site, since uploaded files would then be same-origin content in the admin. The integration refuses the configuration when your astro.config declares a site it can check against. See Security Model.

  3. Allow browser uploads in the bucket's CORS policy

    A PUT from your admin’s origin, with content-type, if-none-match and content-disposition among the allowed request headers: the server signs those terms into the upload URL, so the browser has to send them. Uploads go straight from the browser to the store, which is what keeps them clear of the 4.5 MB (Vercel) and 6 MB (Netlify) function body limits.

  4. Set a lifecycle rule on the .trash/ prefix

    The library keeps it for itself: deletions are moved there rather than dropped, and the media view restores them from it. The rule decides how long a deletion stays undoable, and is the only thing that eventually removes the bytes. See Deleting and restoring.

Writing is always authenticated and always signed. Reading goes through publicUrl, which comes in two shapes.

The ordinary setup: publicUrl points at something anonymous readers can fetch. On R2 that means a custom domain, since the *.r2.dev hostname is rate-limited and not meant for production traffic.

The admin then loads library files straight from that base. It does not ask the CMS server where they are, because the reference already is the URL, so a grid of thumbnails costs no function invocations at all.

Section titled “A closed bucket behind a credentialed CDN (recommended)”

You do not need the bucket itself to be public. Put a CDN in front that holds the credential, deny everything else, and point publicUrl at the CDN:

  • AWS: CloudFront with an Origin Access Control, and a bucket policy allowing only that distribution.
  • Cloudflare R2: a custom domain on the bucket. The bucket is not otherwise reachable.
  • Anything S3-compatible: any CDN that can sign or authenticate to the origin.

As far as the CMS is concerned this is a public library, so nothing else changes and every optimization above still applies. This is the setup to reach for when “the bucket must not be public” is the requirement.

An object store keeps no history, so deleting through the CMS moves the object to a .trash/ prefix instead of dropping it. The media view shows a Trash section listing what can still be brought back, with the path it would return to and when it was deleted. Restore puts it back, refusing if something has taken the name since; Delete permanently is the one media action nothing undoes.

The trash is not a place you can otherwise address: it never appears in the library listing, no path can point into it, and it is reachable only through those two actions.

The assistant can delete media but cannot restore or purge: those are the media view’s alone. That is deliberate, since the point of the trash is to catch a delete that should not have happened, including one the assistant made.

The repository library has no trash and needs none. Its deletions are a commit on the draft branch, so the file is still in Git: discard the changeset to bring it back before publishing, and it stays in history afterwards.

Image optimization and adapter image services

Section titled “Image optimization and adapter image services”
Setup How library images are optimized
Astro’s built-in service, prerendered page Optimized at build into dist/
Astro’s built-in service, on-demand page Optimized per request by /_image
Vercel / Netlify / Cloudflare image service Optimized at the edge

The adapter image services — @astrojs/vercel with imageService: true, @astrojs/netlify’s Image CDN, @astrojs/cloudflare with imageService: "cloudflare" — rewrite an <Image> into a CDN URL that carries your source URL as a parameter, and the CDN fetches that source from its own edge at request time.

The integration already registers publicUrl in astro’s image.remotePatterns, which each adapter translates into its own allowlist (vercel.json image domains, netlify.toml remote_images), so there is nothing further to configure.

How it differs from the repository library

Section titled “How it differs from the repository library”
  • Uploads and deletions are immediate. There is no draft branch holding them, so publishing does not include them and discarding does not undo them. A deleted file stops being served to every visitor at once, even if the entry referencing it is still a draft.
  • Deletion is recoverable. The object is moved to a .trash/ prefix inside the library rather than dropped, and the media view restores it. See Deleting and restoring.
  • Uploads go browser-to-store. The server signs a URL for that key, that byte count and that content type, and the store enforces all three as the write happens (see Security Model). An occupied destination is refused by a signed precondition, and replacing is the admin’s explicit “Replace”/“Overwrite” action. The stored content type comes from the file extension rather than from the uploader, and active types (SVG) get Content-Disposition: attachment signed in as well, so the store serves them as downloads.
  • Content stores public URLs (https://cdn.example.com/photos/hero.png) rather than project paths (/src/assets/photos/hero.png). Astro resolves them itself, in a libraryImage(image) collection field and a markdown image alike. Changing publicUrl later means rewriting the URLs your entries hold.
  • Nothing is bundled. Astro fetches and optimizes the images as remote images instead, so a prerendered page serves the optimized variants and never the originals.
  • Files never move between the libraries. Their references are spelled differently, so a file stays in the library it was uploaded to.

Use the image() helper from the schema function parameter to reference images in frontmatter:

src/content.config.ts
const blog = defineCollection({
loader: glob({ pattern: "**/*.mdx", base: "src/content/blog" }),
schema: ({ image }) =>
z.object({
cover: image().optional(),
}),
});

Astro imports the file itself, so entry.data.cover is ImageMetadata. A plain image() field takes repository files only. Wrap it as libraryImage(image), imported from astronaut-cms/config, to take object-store files too. The field is then typed ImageMetadata | string, and astronaut-cms/Image.astro renders either. See Asset Handling.

Write props as a function to receive the image() and file() helpers:

src/cms.config.ts
import { defineComponent } from "astronaut-cms/config";
import { z } from "zod";
defineComponent({
props: ({ image, file }) =>
z.object({
photo: image(),
attachment: file(),
}),
component: "@/components/Attachment.astro",
});

A component prop is the one asset reference Astro has no mechanism for, so the CMS resolves it. These props are stored as root-absolute path strings (e.g. /src/assets/photo.png) or object-store URLs, and turned into optimized assets at render time. Render them with astronaut-cms/Image.astro or the resolveImage()/resolveFile() helpers from astronaut-cms/assets, see Asset Handling.

The media library supports the following operations through the admin panel:

  • Upload: drag and drop or click to upload files into the library you have open.
  • Rename: change the file name while preserving the extension.
  • Replace: upload a new file to replace an existing one at the same path.
  • Delete: remove a file from the library.

The media picker in the entry editor shows one tab per library.

Check usage reads your content once and then labels every file with how many entries use it, or marks it unused. Unused only narrows the library to those, which is how an object-store library is tidied up: uploads there are immediate, so a discarded draft leaves its uploads behind. The scan is not run until you ask for it, since it reads every entry.

Deleting or renaming a referenced file warns first and names every entry that would break, so neither can silently produce a broken build. The same check applies to the assistant, which refuses both operations while a reference exists.

References are read from your content the way a build reads it — an image() or file() value is an asset because its schema says so — plus a textual pass over bodies, so an image used only in markdown prose or in a Markdoc tag still counts as referenced.

The same scan reports the opposite problem: references pointing at files the library no longer holds. Only schema-declared references are reported there, since a path-shaped string in prose is reason enough to keep a file but not to call an entry broken. For the repository library the build catches these, for the object store nothing else does.