skip to content

In Cloudflare Stream, how do direct creator uploads let instructors upload long lectures from the browser without exposing your API token?

level: middleimportance: must knowfreq 32%

answer

  1. backend asks, browser sends
  2. a one-time upload URL
  3. 200 MB splits POST from tus
  4. limits set in the first request
  5. a duration reserved from storage

basics

~20 s

Your backend, which holds the API token, asks Stream for a one-time upload URL and hands only that URL to the browser, which uploads straight to Stream. Lectures over 200 MB need the tus form of direct creator uploads.

solid answer

~40 s

The backend authenticates the instructor, then calls Stream with its API token. For files under 200 MB, `POST .../stream/direct_upload` with `maxDurationSeconds` returns a one-time `uploadURL` and the video's `uid`, and the browser posts the file there. Long lectures need tus: the backend sends a creation request to `.../stream?direct_user=true` with `Tus-Resumable`, `Upload-Length` and an `Upload-Metadata` header it builds itself, carrying `maxDurationSeconds`, `requiresignedurls` and an `expiry`. Stream returns the upload URL in the `Location` header, and the browser's tus client uploads to it directly. The token never leaves the server, `maxDurationSeconds` is reserved from storage until the video is processed or the link expires, and the backend publishes the lesson when Stream's signed webhook reports the video ready.

code

javascript · 44 lines
javascript
import { requireInstructor } from "./auth.js";

const b64 = (s) => btoa(String.fromCharCode(...new TextEncoder().encode(s)));

export default {
  async fetch(request, env) {
    const instructor = await requireInstructor(request, env);
    if (!instructor) return new Response("Forbidden", { status: 403 });

    const size = request.headers.get("Upload-Length");
    if (!/^\d+$/.test(size ?? "")) return new Response("Upload-Length required", { status: 400 });

    // Built here, never copied from the browser: Stream reads limits from this first request only.
    const metadata = [
      `maxDurationSeconds ${b64("14400")}`,
      "requiresignedurls",
      `name ${b64(request.headers.get("X-Lesson-Title") ?? "lecture")}`,
    ].join(",");

    const res = await fetch(
      `https://api.cloudflare.com/client/v4/accounts/${env.ACCOUNT_ID}/stream?direct_user=true`,
      {
        method: "POST",
        headers: {
          Authorization: `Bearer ${env.STREAM_API_TOKEN}`,
          "Tus-Resumable": "1.0.0",
          "Upload-Length": size,
          "Upload-Metadata": metadata,
          "Upload-Creator": instructor.id,
        },
      },
    );
    if (!res.ok) return new Response("Upload URL not issued", { status: 502 });

    // Store res.headers.get("stream-media-id") on the lesson record here.
    return new Response(null, {
      status: 201,
      headers: {
        Location: res.headers.get("Location"),
        "Access-Control-Expose-Headers": "Location",
      },
    });
  },
};

go deeper

for a junior

Recall the split: the backend holds the token and creates a one-time URL; the browser uploads to Stream with only that URL.

for a middle

Explain the 200 MB split between basic direct uploads and tus, the Location header, and what maxDurationSeconds does to storage.

for a senior

Show the hardening: authenticate before issuing URLs, build Upload-Metadata server-side, set requiresignedurls at creation, and publish only on a verified webhook.

for a principal

Decide what the platform enforces per uploader: duration caps, expiry windows and your own per-instructor quotas set the storage you reserve and the abuse an issued URL can cause.

## Why the token stays on the server A Stream **API token** can upload, edit and delete every video in the account. Putting it in a browser so instructors can upload would hand that power to anyone who opens developer tools. **Direct creator uploads** solve this with a split of duties: 1. The instructor's browser asks *your* backend for permission to upload. 2. Your backend authenticates the instructor and calls Stream with the API token. 3. Stream returns a **one-time upload URL** bound to one future video. 4. The backend passes only that URL to the browser, which uploads the file **straight to Stream**; the bytes never cross your servers. The URL can be used for one upload, and it carries whatever constraints the backend set when creating it, so a stolen URL is worth one constrained upload, not the account. ## Basic direct creator uploads (under 200 MB) The basic form is a `POST` to `/accounts/{account_id}/stream/direct_upload` with a JSON body. `maxDurationSeconds` is required; `expiry`, `creator`, `meta`, `requireSignedURLs`, `allowedOrigins`, `scheduledDeletion`, `thumbnailTimestampPct` and `watermark` are optional. The response holds `result.uploadURL` and `result.uid`. The browser then sends one multipart `POST` to `uploadURL`. A file over **200 MB**, or one that breaks the constraints, is refused with a `4xx` status. Since May 2026 a Worker can do the same through the **Stream binding** (`"stream": {"binding": "STREAM"}` in the Wrangler file) with `env.STREAM.createDirectUpload({ maxDurationSeconds })`, which returns `uploadURL` and `id` with no API token in the Worker. The binding is still marked beta and creates **only basic** upload URLs, so it cannot serve a long lecture. ## Direct creator uploads with tus (long lectures) An hour-long lecture is usually far over 200 MB, so it must use the tus protocol. The flow keeps the same split of duties: 1. The browser's tus client reads the file size and sends a creation request to your backend endpoint with `Upload-Length`. 2. Your backend sends a `POST` to `/accounts/{account_id}/stream?direct_user=true` with the API token, `Tus-Resumable: 1.0.0`, `Upload-Length` and an `Upload-Metadata` header. 3. Stream answers with the one-time upload URL in the **`Location` header**, not in a JSON body, plus a `stream-media-id` header with the video ID. 4. Your backend returns that `Location` (exposed to the browser with `Access-Control-Expose-Headers: Location`), and the tus client uploads the chunks directly to Stream, resuming after any drop. `Upload-Metadata` is a comma-separated list of keys and base64 values separated by a space: `maxDurationSeconds NjAw` for 600 seconds, `expiry` as a base64 RFC 3339 timestamp, and bare flags such as `requiresignedurls`. Stream reads these constraints from the **first** request only and ignores `Upload-Metadata` on the later requests that carry the bytes. That is why the backend should **build** the header itself instead of forwarding whatever the browser sent: a forwarded header lets the client choose its own limits or drop `requiresignedurls`. ## Constraints and what they cost - `maxDurationSeconds` is a cap and a **storage reservation**: that duration is deducted from the account's prepaid storage as soon as the URL is created. After processing, the real duration is counted and the rest released; an unused or expired link, or a video that errors, releases it all. - An upload that breaks the duration cap is refused with a `4xx` status or ends in the error code `ERR_DURATION_EXCEED_CONSTRAINT`. - `creator` ties the video to your internal user ID for search and analytics; for tus uploads the docs set it with the `Upload-Creator` header. - `requireSignedURLs` (or `requiresignedurls` in tus metadata) makes the lesson private from the moment it exists. ## Knowing when the lecture is ready Keep the `uid` (or `stream-media-id`) against the lesson record, then wait for Stream's **webhook**. The account has **one** webhook subscription, set with `PUT .../stream/webhook` and a `notificationUrl`; the response includes a signing `secret`. Stream calls it once processing finishes, successfully or not, and signs each call in a `Webhook-Signature: time=...,sig1=...` header: an HMAC-SHA256, hex-encoded, over the `time` value, a `.` and the raw body. Check the timestamp's age, recompute the signature and compare in constant time before trusting the body. `readyToStream` turns `true` once one quality level plays; for full quality the docs advise publishing when `status.state` is `ready` and `pctComplete` is `100`. Direct-to-storage uploading as a general pattern is covered with file upload ingestion; what is specific here is Stream's one-time URL, the 200 MB split and the metadata rules.

  • Why should the backend build Upload-Metadata itself instead of forwarding the browser's header?
    Stream takes the constraints from the first tus request and ignores `Upload-Metadata` on the later requests that carry the bytes. If the backend forwards what the browser sent, the client chooses `maxDurationSeconds` and whether `requiresignedurls` is present. Building it server-side keeps the duration cap and the privacy flag under your control.
  • What happens to account storage when an instructor creates an upload link and abandons it?
    Creating the link reserves its `maxDurationSeconds` from prepaid storage at once. If the link is never used, the reservation is released when it expires; if the upload errors, it is released too. After a successful upload, the real duration replaces the reservation.
  • How does the backend know a lecture finished encoding, and what must it check first?
    Stream calls the account's single webhook URL once processing ends, with the video's `uid` and `status`. Before trusting it, verify the `Webhook-Signature` header: HMAC-SHA256 over `time`, a dot and the raw body with the webhook secret, compared in constant time, and reject old timestamps.

It is like a prepaid, single-use shipping label: the office buys one label for one parcel with a weight limit and hands it to the sender. The sender can ship that one parcel, but never touches the company account that buys labels.

  • A narrowly scoped Stream API token is safe to ship to the browser.
  • A basic direct creator upload URL accepts multi-gigabyte lecture files.
  • maxDurationSeconds is only a hint and reserves nothing.
  • The tus upload URL comes back in the JSON response body.
  • Forwarding the browser's Upload-Metadata header to Stream is harmless.
  • A webhook body can be trusted without checking Webhook-Signature.

Assumes Stream as of 2026-10-10: the Workers Stream binding (beta since May 2026) creates only basic direct upload URLs, so tus direct uploads still go through the REST API with an API token.