Media API
The Media API covers serving images with on-the-fly CDN transformations. For uploading files and the GraphQL File type, query surface, and lifecycle mutations, see Files API — this page does not restate them.
Uploading
Two paths upload into the media library:
- GraphQL (recommended):
uploadFile, a PUT of the bytes straight to storage, then a POST that says they have landed. Binary bytes never touch the GraphQL endpoint. See Files API. - REST multipart: a single
POSTfor small files that runs all three steps for you. The example below is a script or an integration filling the media library with an admin key; a signed-in user’s upload uses your publishable key and their bearer instead:
POST https://api.foir.dev/api/files/uploadcurl -X POST https://api.foir.dev/api/files/upload \
-H "x-api-key: foir_adm_your_admin_key" \
-F "file=@/path/to/image.jpg" \
-F "folder=campaigns/spring-26"async function uploadFile(file) {
const formData = new FormData();
formData.append("file", file);
const response = await fetch("https://api.foir.dev/api/files/upload", {
method: "POST",
headers: {
"x-api-key": process.env.FOIR_API_KEY,
},
body: formData,
});
return response.json(); // → the stored file record (see below)
}The response is the stored file record in protobuf JSON form, which differs from the GraphQL File in a few names: id, filename, mimeType, size (a string, because it is a 64-bit integer), url, width, height, blurhash, altText, status, createdAt and more. A field with no value is left out. For an image, width, height and blurhash are populated synchronously during the upload and status is FILE_STATUS_READY; a video comes back FILE_STATUS_PENDING, because it is processed afterwards.
Limits
- Maximum file size: 10 MB (the REST path is intended for small files; for large media use the GraphQL pre-signed flow).
- Authentication: an API key with the
files:writescope. - The same rules as the GraphQL flow. The request starts the upload with
uploadFileon the key’s behalf and settles it with the upload’s own token, so the key’sallowedFileTypes, a revoked or expired key and the storage quota refuse it exactly as they refuse those mutations. The response carries the reason:401for a key that is no longer live,403for a missing scope or a file type the key may not upload,413for a file over the size limit or the storage quota.
Supported file types
The REST endpoint validates the declared content type against the file’s magic bytes and accepts:
| Category | Formats |
|---|---|
| Images | JPEG, PNG, GIF, WebP, AVIF, SVG (see below) |
| Video | MP4, WebM, MOV |
| Audio | MP3, WAV, OGG |
| Documents | PDF, JSON, CSV |
| Fonts | WOFF, WOFF2 |
| Archives | ZIP |
XML is not accepted, and neither is HTML, XHTML or JavaScript. An XML document renders as a document in a browser, and the presigned upload pins the object’s Content-Type so the CDN would serve it back as one, which would put an executable page on a Foir origin. The endpoint refuses these with 415 before anything is sent to storage.
SVG is accepted and is treated as a special case. It is a real image format, so it is stored and renders normally inside an <img>. But it also runs script when opened as a top-level document, so the serving edge sends it with Content-Disposition: attachment and a script-blocking Content-Security-Policy. Navigating straight to an SVG’s URL downloads it rather than rendering it.
Image Transformations
Image URLs include an opaque ?t= token the platform mints at resolution time. The token encodes the size preset and any per-usage crop/focal data. Free-form ?width=…&fit=… query parameters are not honoured — only the platform’s own tokens trigger transforms.
URL format
https://cdn.foir.dev/{fileId}?t=eyJzIjoibWVkaXVtIn0The ?t= value is a base64url-encoded JSON object:
{ "s": "medium", "c": "10,10,80,80", "f": "0.5,0.4", "fmt": "avif" }| Field | Meaning | Format |
|---|---|---|
s | Size preset (long-edge width in px) | thumbnail (160) / small (640) / medium (1024) / large (1280) / xlarge (1920) / 2xl (2560) / 3xl (3840) / 4xl (5120) |
c | Crop rectangle | x,y,width,height as 0–100 percentages |
f | Focal point | x,y as 0–1 floats |
fmt | Output format | webp / avif / jpeg / png |
All four fields are optional. A token with only s resizes to a fixed long-edge width; adding c applies a per-usage crop before resize; f controls smart-crop fallback; fmt names the output format.
Choosing the output format
Format is not negotiated. The Accept header is not consulted at all: the format comes from the fmt field inside the token, and a token that does not name one gets the media edge’s default, WebP.
That is deliberate rather than an omission. One URL has exactly one representation, so the CDN can cache a transform without varying on Accept — which its standard cache ignores in any case, meaning an Accept-dependent response would be served to the wrong clients.
You choose the format when you ask for the image, by naming it on the variants field:
{
page(id: "...") {
hero { variants(format: AVIF) { url width height } }
}
}Through the data client you take a different route. format is a field
argument, and the client compiles a fixed selection with no way to pass one, so
variants always arrives as the default tier set. Read the arg-less avif and
webp fields instead — the same synthesised tiers, no argument needed:
const page = await foir.page.findUnique({ id });
page.hero.avif.large.url; // the AVIF tier set
page.hero.webp.large.url; // and the WebP one, from the same readAn image value is expanded whole, so both tier sets arrive on one read. See Resolved image values.
Why opaque tokens
Free-form transform parameters would let scrapers synthesise arbitrary variants and burn through CDN-side image-resize bills. The token grammar is opaque enough that only URLs the platform emits hit the transform pipeline; unknown query strings return the original image.
Resolved image values
The platform emits transform URLs automatically when you resolve image fields. Don’t construct ?t= tokens client-side: let the API response carry them. An image field resolves to an Image:
query {
product(naturalKey: "blue-widget") {
hero { # Image
url # https://cdn.foir.dev/file_abc?t=… (default tier)
width
height
alt
blurhash
dominantColor
variants(format: WEBP) { # responsive tiers the platform pre-emits
thumbnail { size format url width height }
small { size format url width height }
medium { size format url width height }
large { size format url width height }
xlarge { size format url width height }
}
}
}
}Each tier is an ImageVariant object — not a bare URL string — so it requires a sub-selection. Its fields are size (the tier name), format (the rendered format), url, and the true rendered width/height (capped at the source and, for cropped images, derived from the crop aspect — so you can render without layout shift).
The same read through the data client:
const product = await foir.product.findUnique({ naturalKey: 'blue-widget' });
product.hero?.url; // default tier
product.hero?.webp?.large; // an ImageVariant, already resolvedhero arrives as a complete Image, every scalar plus the tier sets, because image values are leaves for selection purposes and are expanded whole. That is convenient and it is not free: an image field is a large part of a record’s payload once the tiers are counted, so omit: ['hero'] is the lever on reads that do not render it.
One thing does not carry over. The format described below is a field argument on variants, and the data client compiles a fixed selection with no way to pass one, so it always takes the default tier set. Read the arg-less webp and avif fields instead — same synthesised tiers, no argument, and one read drives a whole <picture>.
The variants(format: …) field takes an optional format argument — one of WEBP (the default), AVIF, JPEG, or PNG — that selects the format for the whole tier set. Each tier is a distinct, CDN-cacheable URL per format, so to drive a <picture> query the set once per format using aliases:
hero {
webp: variants(format: WEBP) { large { url width height } }
avif: variants(format: AVIF) { large { url width height } }
}The variants object also exposes the larger tiers under _2xl, _3xl, and _4xl (a GraphQL identifier can’t start with a digit, hence the leading underscore).
<picture>
<source srcset="https://cdn.foir.dev/file_abc?t=eyJzIjoibGFyZ2UifQ" media="(min-width: 1024px)" />
<source srcset="https://cdn.foir.dev/file_abc?t=eyJzIjoibWVkaXVtIn0" media="(min-width: 640px)" />
<img src="https://cdn.foir.dev/file_abc?t=eyJzIjoic21hbGwifQ" alt="..." loading="lazy" />
</picture>Blurhash placeholders
Resolved image values carry a blurhash field — a compact string encoding of a blurred placeholder. Use it to display a low-resolution preview while the full image loads.
import { Blurhash } from "react-blurhash";
import { useState } from "react";
function ImageWithPlaceholder({ image }) {
const [loaded, setLoaded] = useState(false);
return (
<div style={{ position: "relative" }}>
{!loaded && image.blurhash && (
<Blurhash hash={image.blurhash} width={400} height={300} />
)}
<img
src={image.url}
alt={image.alt}
onLoad={() => setLoaded(true)}
style={{ display: loaded ? "block" : "none" }}
/>
</div>
);
}Related
- Files API: uploads, the
Filetype, listing, and lifecycle mutations (deleteFile,undeleteFile,purgeFile). - Media & Files — feature overview.