Back to Cloudflare

Deliver Images and Video With the Right Media Pipeline

November 4, 2026 Updated November 6, 2026 Wasil Zafar 24 min read

Choose responsive images, streaming, and access controls

Table of Contents

  1. Images Need Sizes, Formats, and Access Policy
  2. Cloudflare Images and Transformation Workflows
  3. Stream Handles Video Ingestion and Playback
  4. Media Authorization and Cost Drivers
  5. Design a Responsive Gallery and Video Playback Page
  6. Check Access, Image Dimensions, and Playback Behavior

Images Need Sizes, Formats, and Access Policy

Imagine a museum publishes 12,000 archival photographs and a few recorded tours. The first version points every page at the original scan. On a phone, a 6,000-pixel photograph is downloaded into a 390-pixel card, and the page's largest image arrives late.

The fix is not one product. It is three separate decisions:

  • Geometry: which pixels are needed for this slot and screen?
  • Encoding: which format and quality should carry them?
  • Authorization: who may fetch this rendition, and for how long?

A print shop keeps one high-resolution negative and fills orders for different print sizes. Media delivery works the same way: store once, derive many, authorize each delivery.

The source image or master is the original you keep for durability. A variant is a named output recipe, such as thumbnail at 320 pixels. A transformation is a request to produce an output using parameters such as width, fit, format, and quality. Format negotiation chooses an encoding the browser can decode, usually from its Accept header. A signed URL is a capability URL: possession, plus a valid signature and usually an expiry, is permission to fetch.

Figure 1 separates the request paths so failures land on the right layer.

Images Need Sizes, Formats, and Access Policy
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    B[Browser: viewport, DPR, Accept] --> Q{Which URL?}
    Q -->|original object| R[(R2 or origin master)]
    Q -->|variant request| E[Edge: parse variant and params]
    E --> A{Signed URL required?}
    A -->|no| C{Cache hit for source + params?}
    A -->|yes| V{exp and signature valid?}
    V -->|no| D[Refuse delivery]
    V -->|yes| C
    C -->|yes| S[Serve encoded variant]
    C -->|no| O[Fetch source image]
    O -->|missing or 4xx| X[9404 or 9408 error]
    O -->|ok| T[Resize, encode, store derived object]
    T --> S
    S --> B
    classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
    classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
    classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
    classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
    classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
    class E primary;
    class B,Q,A,D,S,O,T secondary;
    class C,V ok;
    class X danger;

Figure 1 also shows why "put a CDN in front" is incomplete. A CDN caches an object; it cannot invent a missing size unless something performs the derivation. Cloudflare offers four related tools: raw R2 objects, transformations for images stored elsewhere, hosted Images with variants, and Stream for video.

Figure 2 turns the flow into boundaries. The browser owns viewport, pixel density, and Accept. The edge owns derivation, cache lookup, and authorization. Storage owns the master bytes.

Media delivery layers: browser, Cloudflare edge, and source storage A browser requests a variant from the edge. The edge checks authorization, looks up a cached derived image, and on a miss fetches the master from R2, Images storage, or an origin. Browser viewport and DPR Accept header srcset and sizes Needs: right pixels, right format, permission Cloudflare edge 1. Authorization check 2. Cache lookup 3. Derive and encode Cache key: source + parameters Source storage R2 bucket Images hosted storage existing web origin Stores masters and durable originals request miss bytes variant Each layer fails differently: layout, policy, or storage.

Cloudflare Images and Transformation Workflows

Suppose the museum keeps its masters in R2. It has four plausible designs, and they differ in who derives the rendition and what the bill counts (Images pricing, transformations overview, Stream pricing).

OptionWhat you storeDerivationAccess controlBilling unitBest fit
Raw R2 objectOriginal bytes, any sizeNone; your app or Worker builds itPublic custom domain or presigned R2 requestStorage and operations; egress freeMasters, downloads, non-image assets
Image TransformationsOriginal in R2 or another allowed originOn-demand resize and format conversion via /cdn-cgi/image/Zone rules, origin allowlist, WAFUnique source-plus-parameter transformations per monthLarge libraries you already host
Hosted ImagesImage uploaded to Images, 10 MB per fileNamed variants, up to 100, or custom optionsPer-image signed URLs; variants can be forced publicImages stored plus images deliveredManaged upload and private delivery
StreamVideo original uploaded or fetched by linkTranscoding and packaging into HLS and DASHSigned playback tokens and allowed embed originsMinutes stored plus minutes deliveredOn-demand and live video

The first row is the control case. R2 stores durable objects and charges no egress, but a public custom domain serves the object you uploaded, not a resized version. Cache rules make repeat delivery cheaper; they cannot change the pixels (R2 pricing, public buckets).

# Masters bucket plus the hostname that serves raw objects.
resource "cloudflare_r2_bucket" "masters" {
  account_id = var.account_id
  name       = "museum-masters"
  location   = "weur"
}

resource "cloudflare_r2_custom_domain" "gallery" {
  account_id  = var.account_id
  bucket_name = cloudflare_r2_bucket.masters.name
  domain      = "images.example.com"
  zone_id     = var.zone_id
  enabled     = true
}
# Upload a master; the custom domain returns these exact bytes.
wrangler r2 object put museum-masters/gallery/room-12.jpg --file ./room-12.jpg

The second row derives renditions at request time. A transformation URL names its options before its source, so the edge can parse width, fit, and format from the path. On a hit it serves the stored rendition without touching the origin; on a miss it fetches, encodes, caches, and serves (transformations overview).

// Build the same transformation URL in a Worker or a build step.
const zone = "https://www.example.com";
const options = "width=640,format=auto";
const source = "gallery/room-12.jpg";

const variant = `${zone}/cdn-cgi/image/${options}/${source}`;
# Ask twice and compare the cache status of the same variant.
for i in 1 2; do
  curl -sI "https://www.example.com/cdn-cgi/image/width=640,format=auto/gallery/room-12.jpg" \
    | grep -i "cf-cache-status"
done

Hosted Images trades control for management. The third row moves the bytes into Images storage and gives you named variants. Hosted images default to format=auto, support up to 100 predefined variants, and can require signed URLs per image or variant (create variants). Upload once, then request https://imagedelivery.net/<ACCOUNT_HASH>/<IMAGE_ID>/<VARIANT>. The tradeoff is a 10 MB per-file upload limit for hosted images, versus 100 MB for remote transformation sources (limits).

Quota stops new work, not cached work

After the documented free-plan allowance of 5,000 unique transformations in a month, cached transformations keep serving, new ones are rejected with 9422, and the original is the fallback. Parameter validation fails earlier with 9401, while a missing source fails later in the same flow, so triage the three as separate classes (Images pricing, troubleshooting).

Figure 3 traces the workflow and its failure branches.

Cloudflare Images and Transformation Workflows
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
sequenceDiagram
    participant B as Browser
    participant E as Edge
    participant C as Cache
    participant O as Source origin
    B->>E: GET variant with width and format
    E->>E: Validate parameters and quota
    alt Invalid or over quota
        E-->>B: 9401 or 9422 error
    else Valid request
        E->>C: Look up source plus parameters
        alt Cache hit
            C-->>E: Cached derived object
            E-->>B: 200 with Cf-Resized header
        else Cache miss
            E->>O: Conditional GET for source
            alt Source missing or denied
                O-->>E: 404 or 403
                E-->>B: 9404 or 9408 error
            else Source available
                O-->>E: 200 original bytes
                E->>E: Resize, encode, store
                E-->>B: 200 derived object
            end
        end
    end
    Note over B,E: New width or new source URL
means a new unique transformation

Responsive markup lets the browser choose. List candidates in srcset with width descriptors and describe the slot with sizes; the server does not guess the device. Cloudflare also supports width=auto, which selects from client hints or a user-agent fallback using default breakpoints of 320, 768, 960, and 1200 pixels, and dpr up to 2 for high-density screens (make responsive images, features).

Format negotiation follows the client. format=auto serves the most efficient format the browser advertises, falling back when AVIF encoding would be too slow or the image too large. A custom Worker that negotiates itself must read Accept; the edge will not infer it (features).

The product boundary matters. Transformations are enabled per zone, and the default source policy accepts only images from that zone. Hosted storage is a paid-plan capability; the free plan includes transformations with the 5,000-unique allowance. AVIF input is Enterprise-only, and private hosted images do not support custom paths. Confirm the current plan matrix before designing around these (pricing, limits, private images).

A cost sketch makes the tradeoff concrete. If 12,000 images are requested at six widths, that is 72,000 unique transformations. The first 5,000 are included, and 67,000 at $0.50 per 1,000 is about $33.50. The same library in R2 at 4 MB per file is 48 GB; 38 billable GB at $0.015 per GB-month is about $0.57. These are list-price estimates, not quotes. Transformation count, not stored bytes, often dominates an image bill.

Stream Handles Video Ingestion and Playback

Video is not a large image. A two-hour MP4 forces the player to fetch a container with interleaved metadata and seek within a growing file; changing quality means starting another file. Adaptive streaming replaces that with a manifest of renditions and short segments the player can switch between as throughput and buffer health change.

BehaviorProgressive MP4Segmented HLS or DASH
What the player fetchesOne file, read with range requestsA manifest, then short segments
Quality switchingRestart from a different fileSwitch at the next segment boundary
StartupWaits on container metadata and a growing bufferStarts once the first segments are buffered
SeekingJumps inside one large objectFetches the segment that covers the target
CachingOne large object, partially cachedEach segment is its own cache entry
Best fitShort clips, downloads, archivalLong or live playback on mixed networks

Adaptive streaming is what lets a phone on a train keep playing while a desktop receives a sharper stream.

Cloudflare Stream owns that pipeline. Upload a file, provide a URL, or issue a one-time direct-creator link. Stream accepts MP4, MKV, MOV, AVI, WebM, MPEG-TS, and other common containers, with a 30 GB maximum, and re-encodes into HLS and DASH renditions (upload videos). Ingestion and encoding are not billed separately. Storage is prepaid at $5 per 1,000 minutes; delivery is post-paid at $1 per 1,000 minutes (Stream pricing).

Direct creator upload keeps bytes off your server. Your backend mints a one-time URL, the browser uploads straight to Stream, and the reservation is released when the upload completes or expires (direct creator uploads).

// Mint a one-time upload URL; the browser sends the file to uploadURL.
const res = await fetch(
  `https://api.cloudflare.com/client/v4/accounts/${env.ACCOUNT_ID}/stream/direct_upload`,
  {
    method: "POST",
    headers: {
      Authorization: `Bearer ${env.CF_API_TOKEN}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ maxDurationSeconds: 1800, requireSignedURLs: true }),
  },
);
const { result } = await res.json();
# Same call from a terminal; the response carries the one-time uploadURL.
curl -X POST "https://api.cloudflare.com/client/v4/accounts/$ACCOUNT_ID/stream/direct_upload" \
  -H "Authorization: Bearer $CF_API_TOKEN" \
  -H "Content-Type: application/json" \
  --data '{"maxDurationSeconds":1800,"requireSignedURLs":true}'

A simple POST is capped at 200 MB, so larger or unreliable connections should use resumable tus instead.

Playback uses the Stream Player or your own HLS or DASH player. The manifest lists the renditions; the player chooses. clientBandwidthHint returns the rendition closest to a requested bitrate, but it is a diagnostic override, not a production default (use your own player).

A token is not a playback pipeline

A signed URL is not a substitute for a playback pipeline. A long-lived token in front of a single 2 GB MP4 still gives viewers a progressive download with no adaptive renditions; the token controls who may fetch the file, not whether playback starts quickly. Conversely, HLS does not make a video private unless requests are actually authorized.

Video failures split into two classes. Packaging problems appear as slow startup, buffering, or an undecodable stream. Authorization problems appear as a manifest that loads but segments that fail, or an embed that works on one domain and not another. Stream's allowed-origin setting controls which domains may embed a video; signed tokens control which viewers may request manifests and segments (securing your Stream).

A realistic scenario: 300 recorded tours, eight minutes each, are 2,400 minutes of storage, rounded into three $5 blocks, or $15 per month. At 20,000 complete views, 160,000 minutes delivered costs $160. A single 1080p MP4 at roughly 5 Mbps is about 300 MB per view, or 6 TB for the same traffic. R2 would not charge egress for those bytes, but it would still serve a progressive file. Stream's price buys transcoding, adaptive renditions, and a player, not cheaper bandwidth.

Media Authorization and Cost Drivers

Authorization is a capability decision. A public gallery image can be fetched by anyone who knows the URL. A private image or video needs a check on every request that returns bytes, not just on the page that contains the embed.

Hosted Images signs each delivery URL. The URL carries an exp timestamp and an HMAC-SHA256 sig query parameter. Your backend holds the signing key, builds the exact path and query string, and returns a short-lived URL. The browser fetches the image directly, without proxying bytes through your Worker. If an image requires signed URLs and the token is missing or invalid, it cannot be accessed unless a variant is explicitly configured to always allow public access (serve private images, Images binding).

Stream swaps the video ID for a signed token. The token appears in player, manifest, and thumbnail URLs, and can carry expiry, not-before, download permission, and IP or country rules. Expiry cannot exceed 24 hours beyond signing time. For low volume, the /token endpoint returns a one-hour token; at scale, sign with a key or use the Workers binding so the key never enters your application (securing your Stream).

Figure 4 contrasts the shapes. A public URL is a permanent capability: anyone who copies it can fetch the object until the object or URL changes. A signed URL adds a verification step; when you set an expiry, the edge checks signature and expiry, and the URL stops working after the window closes. Set that expiry deliberately: the Images binding can generate a signed URL without one if expiresIn is omitted.

Public URL versus signed capability URL Left: a public media URL can be copied and fetched by anyone, and shared caches may retain it. Right: a signed URL carries an expiry and signature that the edge verifies before serving bytes. Public URL /gallery/room-12.jpg anyone with the URL shared cache may retain a copy No expiry. Revocation means changing the object or URL. Signed capability URL ?exp=1790000000&sig=hmac... edge verifies valid: 200 bytes / invalid: refused Short TTL limits replay; sign the exact path and query. Same object, different authorization boundary.

Cost follows the dimensions you vary. Each product meters something different, and the exemption list is where budgets leak (Images pricing, Stream pricing).

MeterBilled perWhat countsWhat does not
Image transformationUnique source plus parameters, per calendar monthWidth, height, fit, and DPR changesRepeated identical requests; format and quality changes do not add uniqueness
Hosted Images storageImage stored per monthEvery image held in Images—
Hosted Images deliverySuccessful response larger than 1,024 bytesDelivered image bytesFailed or tiny responses
Stream storageMinute storedTotal duration held—
Stream deliveryMinute deliveredClient bufferingBrowser-cached playback

Three failure modes deserve design attention.

Cache-busting variants pay twice

Adding ?v=2026-11-04 to every source URL is a common deploy habit. For a transformation, the query string is part of the source identity, so the new URL is a new unique transformation and a cold cache entry. A site that does this on every deploy can pay for the same 72,000 renditions again each month. Version the source object itself, or purge deliberately.

Signing is byte-exact

If you sign one path and serve another, add a parameter after signing, reorder parameters, or use the wrong key, the edge rejects the request. An expiry shorter than the page's cache lifetime produces intermittent failures that look like a CDN problem, and an always-public variant bypasses the signature entirely. Test the exact URL the browser will use.

Format negotiation fails quietly. A Worker or proxy that strips or rewrites the Accept header can make every viewer receive JPEG, or a format the client cannot decode. If you negotiate yourself, send Vary: Accept so shared caches do not serve one client's encoding to another, and test with real browser headers rather than curl defaults.

Guided exercise

Design a Responsive Gallery and Video Playback Page

Design-only. This is a reproducible plan, not a hosted validation. No account was provisioned and no measurements were taken for this article. Run it in your own test account and record your own observations.

RequirementDetail
Account and zoneA test zone you control, HTTPS enabled, dashboard access
TransformationsEnabled on the zone
Hosted ImagesA paid Images plan for storage and signed URLs
StreamA subscription sold as prepaid storage
Fixture-only routeWithout the paid products, use a local static page and local images, and mark hosted steps not run

Inputs. Six images of different aspect ratios, each at least 1600 pixels wide, plus one 30-second video, a static gallery page, and a test bucket or origin for masters. Optionally, a small Worker for signing with the key stored as a secret.

  1. Put the masters in R2 behind a custom domain, or use an existing origin. Keep originals out of the public gallery path if delivery should be private.
  2. Enable transformations on the zone and restrict source origins to your zone. Confirm that a source from an unlisted domain is rejected.
  3. Write the gallery markup with srcset candidates at 400, 800, and 1600 pixels, a matching sizes value, and explicit width and height attributes.
  4. Request each candidate with curl -sI and record status, content type, length, derived-image header, and cf-cache-status. Repeat one request and compare cache status.
  5. Send AVIF, WebP, and JPEG-only Accept headers to the same format=auto URL, and record the returned content types.
  6. If hosted Images is available, upload one private image, create a variant, generate a signed URL with a 60-second expiry, fetch immediately, wait for expiry, and fetch again.
  7. If Stream is available, upload the 30-second video, wait for encoding, create a signed token with a five-minute expiry, and load the embed. Request the manifest with an expired token and record the response.
  8. Add ?v=test1 to one transformation source URL, request it, and compare cache status and any transformation count in the dashboard. Remove it and request the original again.

Expected observations.

CheckExpected result
400-pixel versus 1600-pixel candidateThe smaller candidate returns fewer bytes
Repeated transformationA cache hit; derivation does not re-run
Different Accept headersDifferent content types, with a fallback
Expired signed URLNo bytes returned
Versioned source URLBehaves as a new object

Failure checks.

  • An unsigned request for a private image should fail.
  • A signature with one changed character should fail.
  • A variant marked always-public should still succeed without a token: intended override, design warning.
  • A missing source should produce a 9404-class error.
  • Exceeding the free allowance should produce 9422 for new variants while cached variants serve.

Approximate cost dimensions. Transformations equal source images multiplied by distinct widths; format and quality do not add unique transformations. Hosted storage is $5 per 100,000 images per month, hosted delivery $1 per 100,000 successful responses, Stream storage $5 per 1,000 minutes, and Stream delivery $1 per 1,000 minutes. These are list-price formulas as of 2026-11-04, not a quote.

Cleanup. Delete test images and video, remove R2 objects and the custom domain, disable transformations if unused, purge test URLs, revoke test keys and tokens, and delete the Worker and its secret. Confirm the old URLs no longer serve content.

Check Access, Image Dimensions, and Playback Behavior

Use pass/fail checks another operator can repeat. The verification date is 2026-11-04; the planning baseline is 2026-11-02. No hosted exercise was executed, and no browser, CLI, or product version was tested. These checks become evidence only after you run them.

Pass/fail evidence.

  • Dimensions. Inspect a variant with identify or sips -g pixelWidth -g pixelHeight. Pass if delivered dimensions match the requested width and fit behavior, including DPR. Fail if the original dimensions or an unexpected crop is returned.
  • Format. Request one URL with AVIF, WebP, and JPEG Accept headers. Pass if the content type matches what the client advertised and is decodable. Fail if every client receives one encoding, or an unsupported format.
  • Cache. Request the same variant twice and inspect cf-cache-status. Pass if the second is a hit and derivation is not repeated. Fail if every request misses, usually from a changing query string or a bypass rule.
  • Access. Request a private object with no token, a valid token, an expired token, and a tampered token. Pass if only the valid token returns bytes and the others are non-200. Fail if any invalid request returns the object, or a public variant serves the private object.
  • Playback. Fetch the manifest and confirm it lists multiple renditions with distinct bandwidths. Fetch the first segment and confirm a media content type. Pass if a player starts, switches, and seeks. Measure startup from manifest request to first played segment across several runs, and report the spread. Fail if the manifest is a single progressive file or segments need a token the player never receives.
  • Bypass. Try the R2 public URL, origin hostname, and any r2.dev URL for a private object. Pass if all direct paths are denied or absent.

Self-check with explained answers.

  1. Why does adding ?v=2 to an image URL increase cost? For a transformation, the query string is part of the source URL, so the edge sees a new source-and-parameter combination. That is a new unique transformation and a new cache entry; the old entry cannot be reused.
  2. Why not serve one MP4 from R2 and call it streaming? A progressive MP4 can be cached and range-requested, but it gives the player no renditions to switch between as bandwidth changes. Stream packages the source into segmented HLS and DASH with adaptive bitrate, which is a different delivery model.
  3. Does format=auto bill AVIF and WebP separately? No. format and quality are excluded from uniqueness, so one source and geometry count once even if clients receive different encodings. Width, height, fit, and DPR still count.

Unresolved limitations. Pricing and plan entitlements were checked on 2026-11-04 and can change. Hosted storage, Stream, and Enterprise-only inputs such as AVIF were not exercised. Exact HTTP status codes for every rejected token were not verified; the checks ask for non-200. Cache behavior can differ by colo, rule, and purge history, so one curl is not a global measurement. Browser Accept headers and AVIF support vary. No playback startup or byte-size numbers are claimed as measured results.

References.

Next in the Series

In Build a Mental Model for Realtime Audio and Video, we'll explore Separate interactive sessions from on-demand streaming.